【问题标题】:Sync processes with signal in unix在unix中使用信号同步进程
【发布时间】:2012-10-27 06:51:58
【问题描述】:

如何在 C/C++ 上的 Unix 中将 3 个不同的进程与信号同步? 我需要:第一个过程开始第二个过程。第二个过程开始第三个过程。第三个进程启动后,我想按 1 - 2 - 3 的顺序杀死所有进程。

我不知道为此使用等待、信号、暂停等功能。你可以帮帮我吗?谢谢。

#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

using namespace std;

int main (int argc, char * const argv[]) {

    pid_t three_pid;
    pid_t second_pid;
    pid_t first_pid;

    cout << "child 1 is started" << endl;

    pid_t pid;

    if ((pid = fork()) == -1)
    {
        cout << "fork errror" << endl;
        exit(EXIT_FAILURE);
    }
    else if (pid == 0)
    {
        second_pid = getpid();

        cout << "child 2 is started" << endl;

        pid_t pid2;

        if ((pid2 = fork()) == -1)
        {
            cout << "fork 2 error" << endl;
            exit(EXIT_FAILURE);
        }
        else if (pid2 == 0)
        {
            three_pid = getpid();
            cout << "child 3 is started" << endl;

            cout << "child 3 is TERMINATED" << endl;
        }
        else
        {
            cout << "child 2 is TERMINATED" << endl;
        }
    }
    else
    {
        first_pid = getpid();

        cout << "child 1 is TERMINATED" << endl;
    }
}

【问题讨论】:

    标签: c++ unix synchronization signals fork


    【解决方案1】:

    要以可移植的方式执行此操作,让进程 3(孙子进程)调用 kill(&lt;pid1&gt;, SIGKILL) 并使用 kill(&lt;pid1&gt;, 0) 来测试进程是否仍在运行。如果它消失了,kill() 将失败,errno 设置为ESRCH

    然后让进程 3 对&lt;pid2&gt; 执行相同的操作。

    然后让进程 3 终止。

    【讨论】:

      【解决方案2】:

      您需要在父进程中使用waitpid 等待子进程终止。阅读http://linux.die.net/man/2/waitpid 了解更多详情。像这样:

      int status;
      if (waitpid(cpid, &status, 0) < 0) { // where cpid is child process id
          perror("waitpid");
          exit(EXIT_FAILURE);
      }
      

      您还需要使用_exit(exitCode) 正确终止子进程。阅读http://linux.die.net/man/2/exit了解更多详情。

      编辑:如果您想按 1-2-3 的顺序终止进程,只需等待子进程中的父进程 ID。

      【讨论】:

      • 能否详细说明您的编辑:“...在子进程中等待父进程ID ...
      • 我怀疑孩子在无休止地等待它的父母。
      • @alk: if (waitpid(getppid(), &amp;status, 0) &lt; 0) { // getppid() returns the process ID of the parent of the calling process. perror("waitpid"); exit(EXIT_FAILURE); } 在子进程中会等待父进程终止。
      • 这只适用于相反的方式。逐字逐句来自man waitpid: ... are used to wait for state changes in a child of the calling process ... @mohitjain
      • @alk:你是对的。这是不可能的,我们可以做的一件事是在两个进程之间创建一个管道。当父节点死亡时,管道的末端将被关闭,如果子节点尝试从其末端读取,则会收到一个 SIGPIPE。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2015-04-13
      • 2011-09-06
      • 2017-08-31
      相关资源
      最近更新 更多