簡體   English   中英

waitpid()的示例正在使用中?

[英]Example of waitpid() in use?

我知道waitpid()用於等待進程完成,但是如何使用它呢?

在這里我想做的是,創造兩個孩子並等待第一個孩子完成,然后在退出前殺死第二個孩子。

//Create two children
pid_t child1;
pid_t child2;
child1 = fork();

//wait for child1 to finish, then kill child2
waitpid() ... child1 {
kill(child2) }

waitpid()語法:

pid_t waitpid(pid_t pid, int *status, int options);

pid的值可以是:

  • <-1 :等待進程組ID等於pid絕對值的任何子進程。
  • -1 :等待任何子進程。
  • 0 :等待進程組ID等於調用進程ID的任何子進程。
  • > 0 :等待進程ID等於pid值的子進程。

options的值是以下常量中零或更多的OR:

  • WNOHANG :如果沒有孩子退出,立即返回。
  • WUNTRACED :如果孩子已經停止, WUNTRACED返回。 即使未指定此選項,也會提供已停止的已跟蹤子項的狀態。
  • WCONTINUED :如果通過交付SIGCONT恢復了已停止的孩子, WCONTINUED返回。

如需更多幫助,請使用man waitpid

語法是

pid_t waitpid(pid_t pid, int *statusPtr, int options);

pid是孩子應該等待的過程。

2.statusPtr是指向要存儲終止進程的狀態信息的位置的指針。

3.指定waitpid函數的可選操作。 可以指定以下任一選項標志,也可以將它們與按位包含的OR運算符組合使用:

WNOHANG WUNTRACED WCONTINUED

如果成功,則waitpid返回已報告其狀態的已終止進程的進程ID。 如果不成功,則返回-1。

好在等待

1.Waitpid可以在您有多個子進程時使用,並且您希望等待特定的子進程在父進程恢復之前完成執行

2.waitpid支持工作控制

3.it支持父進程的非阻塞

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

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

暫無
暫無

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

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