Reputation: 73
I'm trying to refresh some C skills, and I'm playing with code to fork and communicate between the two processes.
In the program below, I expected that the child's SIGINT signal would cause the parent to terminate before it printed that the child has died. However, the message "Parent: chlid is dead" is still the last thing to be printed.
Is there something I'm missing?
Thanks.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
int main() {
char *msg;
int forkval, parentpid;
int p2c[2];
pipe(p2c);
forkval = fork();
if (forkval < 0) exit(EXIT_FAILURE);
if (forkval) { /* Parent */
msg = "Parent: reporting\n";
close(p2c[0]);
write(STDOUT_FILENO,msg,strlen(msg));
write(p2c[1], &forkval, sizeof(int));
close(p2c[1]);
wait(NULL);
msg = "Parent: chlid is dead\n";
write(STDOUT_FILENO, msg, strlen(msg));
} else { /* Child */
msg = "Child: reporting\n";
close(p2c[1]);
write(STDOUT_FILENO,msg,strlen(msg));
read(p2c[0], &parentpid, sizeof(int));
close(p2c[0]);
fprintf(stdout, "Child: parent's pid is %i\n", parentpid);
kill(parentpid,SIGINT);
fprintf(stdout, "Child: dying\n");
}
exit(EXIT_SUCCESS);
}
Terminal output:
Parent: reporting
Child: reporting
Child: parent's pid is 10940
Parent: chlid is dead
Upvotes: 2
Views: 549
Reputation: 34829
The nonzero value that fork
returns is the pid
of the child. So the child is killing itself, and that's why you don't see the "Child: dying"
message from the child, but do see the last message from the parent.
Upvotes: 1