as an exercise, I need to use a signal handler, and pipes need to send messages between two processes when receiving a signal. Below is my source code. When I run it, I can make the pipes work, both processes can talk while I call the pipe in their main method (in this case process1 () and process2 ()). But I want to use pipes inside the manipulators. But now the pipes are not working. This is the result I got:
3 - 4 and 5 - 6
Segv at 8825
USR1 at 8824
898 sent to 4
130 received on 3
130
“898” and “130” should be equal, but no. I know that the pipes are working correctly, so I think this has something to do with the signal material ... But what ...?
Source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int fd1[2], fd2[2], status;
int cpid, cpoid;
void process1() {
cpid = getpid();
cpoid = cpid + 1;
close(fd1[0]);
close(fd2[1]);
while (1) {}
}
void process2() {
cpid = getpid();
cpoid = cpid - 1;
close(fd1[1]);
close(fd2[0]);
raise(SIGSEGV);
while (1) {}
}
void send (int msg) {
if (cpid < cpoid) {
write(fd1[1], &msg, 1);
printf("%d sent to %d\n", msg, fd1[1]);
} else {
write(fd2[1], &msg, 1);
printf("%d sent to %d\n", msg, fd2[1]);
}
}
int receive () {
int msg = 0;
if (cpid < cpoid) {
read(fd2[0], &msg, 1);
printf("%d received on %d\n", msg, fd2[0]);
} else {
read(fd1[0], &msg, 1);
printf("%d received on %d\n", msg, fd1[0]);
}
return msg;
}
void segvHandler() {
int y = -1;
printf("Segv at %d\n", cpid);
kill(cpoid, SIGUSR1);
while (y != 898) {
y = receive();
printf("%d\n", y);
}
}
void usr1Handler() {
int x = 898;
printf("USR1 at %d\n", cpid);
send(x);
}
int main (int argc, char *argv[]) {
if (pipe(fd1) < 0) {
fprintf (stderr, "Could not make pipe\n");
return (EXIT_FAILURE);
}
if (pipe(fd2) < 0) {
fprintf (stderr, "Could not make pipe\n");
return (EXIT_FAILURE);
}
printf("%d - %d and %d - %d\n", fd1[0], fd1[1], fd2[0], fd2[1]);
signal(SIGUSR1, usr1Handler);
signal(SIGSEGV, segvHandler);
if (fork() != 0) {
process1();
} else {
process2();
}
waitpid(-1, &status, 0);
return EXIT_SUCCESS;
}