简体   繁体   English

在Unix中将信号与进程同步

[英]Sync processes with signal in unix

How can I sync 3 different processes with signals in Unix on C/C++? 如何在C / C ++上的Unix中将3个不同的进程与信号同步? I need: first process starts second process. 我需要:第一个过程开始第二个过程。 Second process starts third process. 第二个过程开始第三个过程。 After third process is started I want kill all processes in order 1 - 2 - 3. 第三个进程启动后,我要按顺序1-2终止所有进程。

I have no idea about using wait, signal, pause etc functions for this. 我不知道为此使用等待,信号,暂停等功能。 Could you help me? 你可以帮帮我吗? Thanks. 谢谢。

#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;
    }
}

To do this in a portable way let process 3 (the grandchild) call kill(<pid1>, SIGKILL) and use kill(<pid1>, 0) to test if the process is still running. 为此,让进程3(孙代)调用kill(<pid1>, SIGKILL)并使用kill(<pid1>, 0)来测试进程是否仍在运行。 If its gone kill() will fail with errno set to ESRCH . 如果其消失,则errno设置为ESRCH kill()将失败。

Then let process 3 do the same for <pid2> . 然后让进程3对<pid2>做同样的<pid2>

Then let process 3 terminate. 然后让进程3终止。

You need to use waitpid in parent process to wait until child procsee is terminated. 您需要在父进程中使用waitpid来等待子procsee终止。 Read http://linux.die.net/man/2/waitpid for more details. 阅读http://linux.die.net/man/2/waitpid以获得更多详细信息。 Like this: 像这样:

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

Also you need to correctly terminate child process using _exit(exitCode) . 另外,您还需要使用_exit(exitCode)正确终止子进程。 Read http://linux.die.net/man/2/exit for more details. 阅读http://linux.die.net/man/2/exit了解更多详细信息。

EDIT: If you want to to terminate processes in order 1-2-3 just wait for parent process id in child process. 编辑:如果要终止1-2-3顺序的进程,只需在子进程中等待父进程ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM