簡體   English   中英

在Unix中將信號與進程同步

[英]Sync processes with signal in unix

如何在C / C ++上的Unix中將3個不同的進程與信號同步? 我需要:第一個過程開始第二個過程。 第二個過程開始第三個過程。 第三個進程啟動后,我要按順序1-2終止所有進程。

我不知道為此使用等待,信號,暫停等功能。 你可以幫幫我嗎? 謝謝。

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

為此,讓進程3(孫代)調用kill(<pid1>, SIGKILL)並使用kill(<pid1>, 0)來測試進程是否仍在運行。 如果其消失,則errno設置為ESRCH kill()將失敗。

然后讓進程3對<pid2>做同樣的<pid2>

然后讓進程3終止。

您需要在父進程中使用waitpid來等待子procsee終止。 閱讀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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM