【问题标题】:Is there a good way to alter execution order of child processes created with fork()?有没有一种好方法可以改变用 fork() 创建的子进程的执行顺序?
【发布时间】:2018-03-13 09:15:44
【问题描述】:

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

简单示例:

  • 父母用叉子创建了 2 个孩子
  • 儿童
    1. 第一个孩子打印“消息 2”
    2. 第二个孩子打印“消息 1”
  • 完成后,父级打印“End”

由于我们无法确定先执行哪个进程,所以最终结果很有可能是:

消息 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(),它可以工作但不漂亮

【问题讨论】:

标签: c fork


【解决方案1】:

您需要使用实际的进程间通信来实现这一点。

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

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

【讨论】:

  • 谢谢!我研究了可能会起作用的信号量,但最终它引导我找到了共享变量。这样我就可以实现孩子之间的简单交流。
猜你喜欢
  • 1970-01-01
  • 2014-01-10
  • 2010-09-06
  • 1970-01-01
  • 2019-08-29
  • 2012-10-27
  • 2013-06-15
  • 2011-10-05
相关资源
最近更新 更多