如何使用linux在c中使用fork()实现我想要的输出?

时间:2014-07-28 22:36:48

标签: c linux

我知道程序可以多次分叉。我也明白每个子进程都可以使用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;

1 个答案:

答案 0 :(得分:1)

这会给你我认为你想要的。如果你向我们展示了@Jim Garrison建议的奇怪输出,我会有更好的想法。我认为你的输出会来自你不等孩子终止。您无法控制操作系统允许在哪个时间在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;