有没有一种方法可以改变使用fork()创建的子进程的执行顺序?

时间:2017-10-02 09:46:32

标签: c fork

我正在寻找创建子进程,我可以控制它们的处理顺序。

简单示例:

  • Parent使用fork创建2个子项
  • 儿童
    1. 第一个孩子打印"消息2"
    2. 第二个孩子打印"消息1"
  • 完成后,父母打印"结束"

由于我们无法确定哪个流程将首先执行,因此最终结果很可能是:

  

消息2

     

消息1

     

结束

我试图确保第二个孩子在第一个孩子面前执行打印,并且父母在所有孩子之后执行打印。

对于父母来说,使用wait()/ waitpid()函数非常容易。然而,孩子们似乎更难。

以下是我实现目标的想法的实现:

(注意:我对创建子进程仍然很陌生,我可能在这个实现中误解了一些内容)

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

#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

static int init = 0;

void setInitFinished(int sig)
{
    if (sig == SIGUSR1)
        init = 1;
}

int main()
{
    signal(SIGUSR1, setInitFinished);

    pid_t pid1, pid2;
    int status1, status2;

    // CHILD 1
    if (!(pid1 = fork()))
    {
        while (!init); // Waiting all children to be initiated

        // Once all children created, we wait for child 2 to print its message
        int pidOfChild2 = getpid()+1; // I checked, the PID is correct
        waitpid(pidOfChild2, &status1, 0);

        printf("MESSAGE 2\n");
        exit(0);
    }

    // CHILD 2
    if (!(pid2 = fork()))
    {
        while (!init); // Waiting all children to be initiated

        // No need to wait since it's the first message to be printed
        printf("MESSAGE 1\n");
        exit(0);
    }

    // PARENT

    // All children have been created, tell it to all the children
    kill(pid2,SIGUSR1);
    kill(pid1,SIGUSR1);

    // When every child has finished its work, continue parent process
    waitpid(pid1, &status1, 0);
    waitpid(pid2, &status2, 0);

    printf("Parent end\n");

    return 0;
}

在孩子1中我试图用 waitpid(pidOfChild2,...)等孩子2;但它似乎没有用。

我仍然发现了fork功能,所以我很肯定会在这里误解很多东西。

注意:我想避免使用sleep(),它可以工作,但它并不漂亮

1 个答案:

答案 0 :(得分:2)

您需要使用实际的进程间通信来实现此目的。

您似乎认为waitpid()函数与等待进程打印输出有关,但这根本不是它的作用。

在父级中创建semaphore,将其传递给两个子级,让一个孩子在打印前等待信号量,另一个孩子在信号量完成打印后发送信号。

相关问题