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

use*_*864 17 c fork parent-child waitpid

我知道这waitpid()用于等待一个过程完成,但是如何才能完全使用它?

在这里我想做的是,创造两个孩子并等待第一个孩子完成,然后在退出前杀死第二个孩子.

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

//wait for child1 to finish, then kill child2
waitpid() ... child1 {
kill(child2) }
Run Code Online (Sandbox Code Playgroud)

mf_*_*041 25

语法waitpid():

pid_t waitpid(pid_t pid, int *status, int options);
Run Code Online (Sandbox Code Playgroud)

pid可以是:

  • <-1:等待进程组ID等于绝对值的任何子进程pid.
  • -1:等待任何子进程.
  • 0:等待进程组ID等于调用进程ID的任何子进程.
  • > 0:等待进程ID等于值的子进程pid.

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

  • WNOHANG:如果没有孩子退出,立即返回.
  • WUNTRACED:如果孩子已经停止,也会返回.即使未指定此选项,也会提供已停止的已跟踪子项的状态.
  • WCONTINUED:如果已经通过交付恢复了已停止的孩子,也会返回SIGCONT.

如需更多帮助,请使用man waitpid.

  • https://support.sas.com/documentation/onlinedoc/sasc/doc/lr2/waitpid.htm通过示例提供了更详细的信息.我个人仍然无法理解如何从这个问题的2个答案有效地使用waitpid. (4认同)

KAR*_*HAT 13

语法是

pid_t waitpid(pid_t pid, int *statusPtr, int options);
Run Code Online (Sandbox Code Playgroud)

pid是孩子应该等待的过程.

2.statusPtr是指向要存储终止进程的状态信息的位置的指针.

3.指定waitpid函数的可选操作.可以指定以下任一选项标志,也可以将它们与按位包含的OR运算符组合使用:

WNOHANG WUNTRACED WCONTINUED

如果成功,则waitpid返回已报告其状态的已终止进程的进程ID.如果不成功,则返回-1.

好在等待

1.Waitpid可以在您有多个子进程时使用,并且您希望等待特定的子进程在父进程恢复之前完成执行

2.waitpid支持工作控制

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


小智 5

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以稍微解释一下您的答案吗? (4认同)
  • 非常非常糟糕的例子,错误处理和 EINTR 唤醒(经常发生)等未处理。 (3认同)