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

标签 c linux

我知道一个程序可以 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/

相关文章:

c - 为什么 C 中函数类型声明后面有一个星号?

c - 使用 libpcap 查找设备地址

linux - 调用存储在另一个 shell 脚本变量中的 shell 脚本

linux - 在 ubuntu 上使用 "virt-install"创建虚拟机时出现问题,在显示初始信息后挂起

linux - 是否有任何人都可以在 linux 中读/写的共享文件的特殊用户和组?

c - 从文件中逐字读取或一次读取一行并使用 C 拆分字符串更有效率?

c - 了解 extern 的工作原理

c - 一个信号在阻塞模式下中断发送方法

在 Linux 中收集具有不同参数的 C 代码的输出

c - 通过设备名称获取设备标志