簡體   English   中英

如何從父進程獲取子進程的狀態,即它是停止、繼續還是退出? 對於 Linux、C 語言

[英]How do I get the status of a child process from a parent, i.e. has it stopped, continued, or exited? For Linux, C lang

這是 Linux (ubuntu) 中的 C 語言程序。 我一直在試圖弄清楚如何從父母那里獲得子進程的狀態。

我編寫了一個簡單的子進程,它在 25 秒內計數為 25,並將滴答計數輸出到標准 output。 在父進程中,我1> 停止子進程幾秒鍾。 2> 繼續它幾秒鍾,然后3> 殺死子進程。 我想獲取子進程的狀態,為此我一直在使用waitpid() function。 但是,我發現如果我使用這些標志:

等待條件 = WUNTRACED | W續

它確實返回“停止”狀態,但是當它處於繼續 state 時它會掛起。

相反,如果我將標志設置為:

等待條件= WUNTRACED | W續 | 萬航

停止狀態未注冊,但繼續狀態由 waitpid() 注冊。

我試圖讓父母在 state 停止、繼續或退出時識別它。

我有下面的代碼。 有沒有人對此有任何想法? 謝謝!

int waiting4pid()(pid_t processID)
{   
    int waitCondition = WUNTRACED | WCONTINUED;
    int currentState;

    while (waitpid(processID,&currentState,waitCondition) > 0){

        if(WIFCONTINUED(currentState)){
            printf("\n currentState = continued!\n");
        }
        if(WIFSIGNALED(currentState)){
            printf("\n currentState = signaled!\n");            
        }
        if(WIFSTOPPED(currentState)){
            printf("\n currentState = stopped!\n");
        }
        
    }
}

void sigTest()
{ 
    pid_t processID;

    processID = fork();
    if(processID ==0) { // child
       // tmp/loop is an application that counts to 25 in 25 seconds and then exits.
       execlp("tmp/loop", "tmp/loop", NULL);
    }else{ 
        sleep(2);
        printf("\n Stop!");
        kill(processID, SIGSTOP);
        waiting4pid()(processID);
        
        sleep(2);
        printf("\n Continue!");      
        kill(processID,SIGCONT);
        waiting4pid()(processID);
        
        sleep(2);
        printf("\n Kill!"); 
        kill(processID, SIGKILL);
        waiting4pid()(processID);
    }
}

void main() 
{    
    sigTest();
}

為了檢查進程是否退出,請執行以下操作:

if(WIFEXITED(status) {

    // do your stuff

    // you can also check the exit status
    if(WEXITSTATUS(status) != EXIT_SUCCESS) {
        // the child process exited with error
    }
}

正如@kaylum 在問題下的評論中已經提到的那樣, waitpid()調用會阻塞,直到孩子更改 state。 但是您可以通過設置WNOHANG標志調用waitpid() waitpid()修改此行為(如果您需要監視子進程但同時在父進程中執行一些其他操作,這將很有用;或者您可以在單獨的線)。

暫無
暫無

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

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