我知道一个程序可以 fork 多次。我还了解到每个子进程都可以使用 fork 来生成自己的子进程。我正在尝试编写一个创建两个子进程的程序,然后每个子进程应该创建一个自己的子进程。这是我想要的输出:
I'm the child '7786' parent '7785'
I'm the sub-child '7787' parent '7786'
I'm the second child: '7788' parent: '7785'
I'm the second sub-child: '7789' parent: '7788'
这是我的代码。当我有 forks() 时,输出变得很奇怪,我不知道如何处理它
int pid, ppid;
pid =getpid();
ppid = getppid();
printf("I'm the child: %d \t Parent process id:%d\n", pid, ppid);
printf("I'm the sub-child: %d \t Parent process id:%d\n", pid, ppid);
printf("I'm the second child: %d \t Parent process id:%d\n", pid, ppid);
printf("I'm the second sub-child: %d \t Parent process id:%d\n", pid, ppid);
return 0;
最佳答案
这会给你我想你想要的。如果您向我们展示@Jim Garrison 建议的奇怪输出,我会有更好的主意。我认为你的输出将来自你不等待 child 终止。您无法控制操作系统允许哪个进程何时在 CPU 上运行。因此,如果我没有下面的 wait(&status)
命令,则输出可能以任何顺序出现。通过使用 wait
命令,它会强制父级等待其子级完成,然后再继续。因此,下面的代码将按照您在问题中指定的顺序输出您想要的内容。
如果您想了解如何无法控制执行顺序,请删除 wait
命令并多次运行该程序。输出应以随机顺序出现。
int pid1, pid2, subpid1, subpid2, status;
pid1 = fork();
if (pid1 == 0) {
/* First child */
printf("I'm the child: %d \t Parent process id:%d\n", getpid(), getppid());
subpid1 = fork();
if (subpid1 == 0) {
/* First sub-child */
printf("I'm the sub-child: %d \t Parent process id:%d\n", getpid(), getppid());
} else {
wait(&status); /* Wait until sub-child terminates */
}
} else {
wait(&status); /* Wait until child terminates */
pid2 = fork();
if (pid2 == 0) {
/* Second child */
printf("I'm the second child: %d \t Parent process id:%d\n", getpid(), getppid());
subpid2 = fork();
if (subpid2 == 0) {
/* Second sub-child */
printf("I'm the second sub-child: %d \t Parent process id:%d\n", getpid(), getppid());
} else {
wait(&status); /* Wait until second sub-child terminates */
}
} else {
wait(&status); /* Wait until second child terminates */
}
}
return 0;
关于c - 我如何使用linux在c中使用fork()来实现我想要的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005449/