如何在执行进程之前等待子子和 parent?

How to wait a subchild and a parent before executing process?

我的程序是这样表达的:有一个 parent 分叉了一个 child 而这个 child 分叉了另一个 child。所以有一个parent,一个child和一个subchild(即这个subchild的parent是child)。

child 使用 execlp() 执行命令,为了简单起见,我们说日期。 subchild 做同样的事情。

当然 child 会在执行命令之前分叉子child。

我正在寻找 subchild 来在 child 执行它自己的命令后执行命令。此外,在 child 和 subchild 执行了他们的命令后,我希望 parent 继续它自己的过程。

我有两个问题:

这是我当前的实现:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char **argv){
    pid_t pid1, pid2;

    pid1 = fork();

    if (pid1 > 0)
    {
        int status;

        // Wait child
        printf("Parent waiting for child\n");
        waitpid(pid1, &status, 0);
        printf("Parent has waited child\n");

        // Wait subchild
        printf("Parent waiting for subchild\n");
        // Wait sub-child here?
        printf("Parent has waited subchild\n");

        // End
        printf("parent end\n");
    }
    else
    {
        pid2 = fork();

        // Subchild
        if (pid2 == 0) {
            waitpid(getppid(), NULL, 0); // wait child? it doesn't work
            execlp("/bin/date", "date", "+Subchild:\"%d-%m-%y\"", (char *) 0);
            _exit(EXIT_FAILURE);
        }
        // Child
        else {
            execlp("/bin/date", "date", "+Child:\"%d-%m-%y\"", (char *) 0);
            _exit(EXIT_FAILURE);
        }
    }

    return 0;
}

我的两个"problems"是第21行和第33行。

输出如下:

Parent waiting for child
Subchild:"03-10-17"
Child:"03-10-17"
Parent has waited child
Parent waiting for subchild
Parent has waited subchild
parent end

subchild 尽可能快地执行自己......我通过使用共享变量解决了这个问题,但它感觉像是一种解决方法,我仍然遇到 parent 等待子child.

感谢@JonathanLeffler,我可以通过创建管道来解决问题。由于我不知道管道是如何工作的,所以花了一些时间,但最终它比我想象的要容易得多。

@DavidC.Rankin 我阅读了有关 wait 函数的文档,但在那种情况下它似乎没有任何帮助。

谢谢。