Reputation: 23
I want to fork 3 child processes and have each process execute a function and busy wait until they are complete. The 3rd process is a countdown timer so once the runtime reaches 0 I will use an IPC to tell the other processes to exit. I have written the functions besides the IPC part and they run individually but I can't get fork() to create the 3 child processes to each execute a specific function.
int main(int argc, char *argv[]) {
pid_t child_onepid, child_twopid, child_threepid, pid;
for (i = 0; i < 3; ++i) {
pid = fork();
if (pid) {
continue;
} else if (pid == 0 && i == 0) {
show_time();
} else if (pid == 0 && i == 1) {
show_uptime();
} else if (pid == 0 && i == 2) {
show_timer(runtime);
} else {
printf("fork error\n");
exit(1);
}
}
return EXIT_SUCCESS;
}
This is my output
Time: 06/28/2014 18:55:57PM
Timer: 00:09
>Timer: 00:09
6:55pm up 171 day(s), 10:49, 17 users, load average: 0.34, 0.38, 0.43
6:55pm up 171 day(s), 10:49, 17 users, load average: 0.34, 0.38, 0.43
Upvotes: 0
Views: 662
Reputation: 25903
Your code looks fine to me, except your error test will never hit because the if(pid)
will trigger on -1
.
Besides that, are you supper sure that your functions are not returning and then going around their own copy of the for loop, that would explain the output... so I added some break
to make sure of that.
But I've not tested the code.
int main(int argc, char *argv[]) {
pid_t pid;
for (int i = 0; i < 3; ++i) {
pid = fork();
if (pid == -1) {
perror("fork error\n");
exit(EXIT_FAILURE);
} else if (pid > 0)
continue;
} else if (i == 0) {
show_time();
break;
} else if (i == 1) {
show_uptime();
break;
} else if (i == 2) {
show_timer(runtime);
break;
}
}
return EXIT_SUCCESS;
}
Upvotes: 2