用c语言编写程序,用fork
发布网友
发布时间:2022-05-30 17:52
我来回答
共1个回答
热心网友
时间:2023-10-24 15:10
唉,这种题目也就是教科书,大体思路就是记录fork的返回值
如果是0,那就是子进程,如果大于零就是进程本身,然后嵌套条件语句
#include <stdio.h>
#include <unistd.h>
void show (char *name) {
printf ("PID:%5u %s\n", getppid(), getpid (), name);
sleep (30);
}
int main () {
pid_t c1 = fork ();
if (-1 == c1)
perror ("fail to create child 1");
else if (0 == c1) {
show ("child1");
}
else {
pid_t c2 = fork ();
if (-1 == c2)
perror ("fail to create child 2");
else if (0 == c2) {
pid_t g1 = fork ();
if (-1 == g1)
perror ("fail to create child of child 2");
else if (0 == g1) {
pid_t gg1 = fork ();
if (-1 == gg1)
perror ("fail to create grand-child of child 2");
else if (0 == gg1) {
show ("grand-child of child 2");
}
else {
show ("child of child 2");
}
}
else {
show ("child2");
}
}
else {
pid_t c3 = fork ();
if (-1 == c3)
perror ("fail to create child 3");
else if (0 == c3) {
show ("child3");
}
else
show ("main");
}
}
}