首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在unix中使用信号同步进程

问在unix中使用信号同步进程
EN

Stack Overflow用户
提问于 2012-10-27 14:51:59
回答 2查看 855关注 0票数 0

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

我不知道如何使用等待,信号,暂停等功能。你能帮我一下吗?谢谢。

代码语言:javascript
复制
#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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-27 15:51:13

要以可移植的方式做到这一点,让进程3(孙子进程)调用kill(<pid1>, SIGKILL)并使用kill(<pid1>, 0)测试进程是否仍在运行。如果它消失了,kill()将失败,并将errno设置为ESRCH。

然后让进程3对<pid2>执行相同的操作。

然后让进程3终止。

票数 3
EN

Stack Overflow用户

发布于 2012-10-27 15:36:27

您需要在父进程中使用waitpid来等待到子进程被终止。有关更多详细信息,请阅读http://linux.die.net/man/2/waitpid。如下所示:

代码语言:javascript
复制
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。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13097970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档