【问题标题】:How to terminate several processes in C with fork()?如何使用 fork() 终止 C 中的多个进程?
【发布时间】:2016-09-16 23:04:44
【问题描述】:

我正在做一个关于 Unix 进程的项目,使用 languaje C。该项目是使用等待(函数 fork())exit() 来表示进程树。

我的程序的输出应该是我:

  1. 父亲:PID1 - 你好
  2. 孩子 1:PID2 - 你好
  3. GrandChildren1.1:PID3 - 你好,再见
  4. GrandChildren1.2:PID4 - 你好,再见
  5. 儿童 1:PID2 - 再见
  6. Children2:Pid6 - 你好
  7. GrandChildren2.1:Pid7 - 你好,再见
  8. Children2:Pid6 - 再见
  9. 父亲:PID1 - 再见

这个输出明白了吧。 我将以下代码安排到流程的开头,但没有安排它们如何完成流程:

main() {

    if(fork())
    {
        // 1
        printf("1. Father:Pid1 - Hello\n");
        if(fork())
        {
            // 2
            printf("2. Children1:Pid2 - Hello\n");
            if(fork())
            {
                // 4
                printf("3. GrandChildren1.1:Pid3 - Hello and GoodBye\n");
            }
            else{}

            wait(1);

            if (fork())
            {
                 printf("3. GrandChildren1.2:Pid4 - Hello and GoodBye\n");
            }
            else {}
        }
        else
        {
            printf("4. Children1:Pid2 - GoodBye\n");
        }
    }
    else{
        if(fork())
        {
            // 3}
            printf("6. Children2:Pid6 - Hello\n");
            if (fork())
            {
                printf("6. GrandChildren2.1:Pid7 - Hello and GoodBye\n");
            }
            else{}
    }
    else{}
    }

    pause();
    return 0;
}

这个输出明白了吧。 我将以下代码安排到流程的开头,但没有安排它们如何完成流程:

比如不知道怎么做完PID2,看到你打印2个孙子的时候,我要了。

怎么可能?

问候

【问题讨论】:

  • 了解kill() 函数和信号处理。
  • wait(1); 并阅读wait man page,因为这不是正确的称呼方式。
  • 你好iharob,我用的不是kill,只是fork,wait,waitpid,exit,write,指令。
  • 你应该在你的问题中解释一下,如果它必须没有杀戮

标签: c operating-system fork


【解决方案1】:

我不确定我是否得到了您的问题,无论如何,按照我的理解,您需要规范执行流程。有几种方法:

等待(),等待PID(), 杀(), sigaction()

您可以通过查看它们的手册页了解它们的工作原理。

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2015-11-10
    相关资源
    最近更新 更多