Reputation: 201
I'm trying to implement a program that forks multiple times. The resulting child processes should send their IDs to another program, the receiver program, which should then proceed to kill them one by one.
This is the main program:
int main()
{
int fd1;
int fd2;
int fd3;
int fd4;
int test;
int set;
char *myfifo = "/home/test1";
for(int i=0; i <7; i++) {
if(fork()==0) {
test = mkfifo(myfifo, 0600);
if(((test==0)||(test==-1))&&(errno!=EEXIST)) {
printf("No such instance exists, terminating...\n");
exit(1);
}
else {
set = getpid();
fd2 = open(myfifo,O_WRONLY);
write(fd2, &set,sizeof(int));
close(fd2);
}
exit(0);
}
}
for(int k=0; k<7; k++)
wait(NULL);
return 0;
}
This is the receiver program:
int main()
{
int fd;
int fd2;
int fd5;
int test;
char *myfifo = "/home/test1";
test = mkfifo(myfifo, 0600);
if(test==-1) {
printf("No such instance exists, terminating...\n");
exit(1);
}
else {
for(int x=1; x <=7; x++) {
int contid;
fd5 = open(myfifo, O_RDONLY);
read(fd5, &contid, sizeof(int));
printf("Contestant with ID %d has joined!\n", contid);
kill(contid, SIGKILL);
printf("Goodbye ID %d\n",contid);
close(fd5);
}
}
return 0;
}
I was expecting an output along the lines of:
Contestant with ID 18230 has joined!
Goodbye ID 18230.
Contestant with ID 18229 has joined!
Goodbye ID 18229.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18227 has joined!
Goodbye ID 18227.
But instead I'm getting this:
Contestant with ID 18230 has joined!
Goodbye ID 18230.
Contestant with ID 18229 has joined!
Goodbye ID 18229.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18231 has joined!
Goodbye ID 18231.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18228 has joined!
Goodbye ID 18228.
Contestant with ID 18227 has joined!
Goodbye ID 18227.
Why are there child processes that "rejoin" even after being supposedly killed? What could've been the root of this problem? Your help would be greatly appreciated.
Upvotes: 0
Views: 99