wait & waitpid
- 功能:收集子进程的终止状态信息
- 原型:
pid_t wait(int *wstatus);
pid_t waitpid(pid_t pid, int *wstatus, int options);
- 参数:
1)int* wstatus
2)pid
3)option:0,一直等待;WNOHANG,不阻塞 - 返回值:
成功:返回终止子进程的 pid(waitpid:如果设置了 WNOHANG, 并且没有子进程的状态发生修改,返回 0)
失败:返回-1,并会设置errno - DO
#include <func.h>
void print_wstatus(int status) {
if (WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
printf("exit_code = %d", exit_code);
} else if (WIFSIGNALED(status)) {
int signo = WTERMSIG(status);
printf("term_sig = %d", signo);
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
printf(" (core dump)");
}
#endif
}
printf("\n");
}
int main(int argc, char* argv[]) {
pid_t pid = fork();
switch (pid) {
case -1:
error(1, errno, "fork");
case 0:
printf("CHILD: pid = %d\n", getpid());
while (1);
default: {
int status;
pid_t childPid = wait(&status);
if (childPid > 0) {
printf("PARENT: %d terminated\n", childPid);
print_wstatus(status);
}
exit(0);
}
}
return 0;
}
#include <func.h>
void print_wstatus(int status) {
if (WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
printf("exit_code = %d", exit_code);
} else if (WIFSIGNALED(status)) {
int signo = WTERMSIG(status);
printf("term_sig = %d", signo);
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
printf(" (code dump)");
}
#endif
}
printf("\n");
}
int main(int argc, char* argv[]) {
pid_t pid = fork();
switch (pid) {
case -1:
error(1, errno, "fork");
case 0:
printf("CHILD: pid = %d\n", getpid());
while (1);
default: {
int status;
pid_t childPid = waitpid(-1, &status, 0);
if (childPid > 0) {
printf("PARENT: %d terminated\n", childPid);
print_wstatus(status);
} else if (childPid == 0) {
printf("PARENT: no child changed state\n");
} else {
error(1, 0, "waitpid");
}
exit(0);
}
}
return 0;
}