#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv) {
for(int i = 0; i < 10; i++) {
pid_t pid = fork();
if(pid == 0) {
while(1) {
pid_t pid2 = fork();
wait(NULL);
}
}
}
wait(NULL);
return(0);
}
基本上,该程序会运行多个 hello world 进程并使用 ctrl+C 关闭。我将如何处理等待错误?像错误(等待)。我认为我必须使用 int status 而不是 NULL,但不确定在涉及孤儿进程时如何去做。
给定的代码是
$ gcc -Wall above.c
$ ./a.out
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
^C (until ctrl C is hit)
$
最佳答案
函数 perror
仅在您知道函数失败并且
errno
已设置,因此您要打印一条错误消息。你通常写
perror("something failed")
紧跟在可能失败的函数之后 and
设置 errno
(该函数的文档会告诉您是否
函数设置 errno
失败)。
man perror
SYNOPSIS
#include <stdio.h> void perror(const char *s); #include <errno.h>
DESCRIPTION
The
perror()
function produces a message on standard error describing the last error encountered during a call to a system or library function....
这与 wait
无关,它是参数,只有在
wait
失败,您想要打印有关 wait
失败的错误消息。
man wait
SYNOPSIS
#include <sys/types.h> #include <sys/wait.h> pid_t wait(int *wstatus); pid_t waitpid(pid_t pid, int *wstatus, int options);
DESCRIPTION
All of these system calls are used to wait for state changes in a child of the calling process... ...
wait()
andwaitpid()
The
wait()
system call suspends execution of the calling process until one of its children terminates. The callwait(&wstatus)
is equivalent to:waitpid(-1, &wstatus, 0);
...
RETURN VALUE
wait()
: on success, returns the process ID of the terminated child; on error, -1 is returned....
Each of these calls sets
errno
to an appropriate value in the case of an error.
如果你只是想等待一个 child 退出,你可以做wait(NULL)
。
但是,如果您想知道退出的 child 的状态,那么您有
将指针传递给 int
。
int wstatus;
pid_t wp = wait(&wstatus);
if(wp == -1)
{
// here I use perror because if wait returns -1 then there
// was an error and errno is set
perror("could not wait for child\n");
exit(1);
}
if(WIFEXITED(wstatus))
printf("Child with pid %d exited normally with status %d\n", wp, WEXITSTATUS(wstatus));
else
printf("Child with pid %d exited abnormally\n", wp);
我个人更喜欢 waitpid
而不是 wait
,它可以让你更好地控制
child 你在等。
参见 man wait
关于c - 我在哪里放置 perror ("wait") 和 fork 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419299/