一个进程可以通过调用waitpid()函数来等待他的子进程的终止或停止
waitpid()会暂时停止目前进程的执行,直到有信号来到或子进程结束。
pid_t waitpid(pid_t pid,int *status,int options);
如果成功,则为子进程的PID 如果WHOHANG 则为0 如果其他错误 为-1
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
pid_t childpid;
int status;
childpid = fork();
if (childpid < 0) {
perror("fork()");
exit(EXIT_FAILURE);
} else if (childpid == 0) {
puts("In child process");
sleep(3);//让子进程睡眠3秒,看看父进程的行为
printf("\tchild pid = %d\n", getpid());
printf("\tchild ppid = %d\n", getppid());
exit(EXIT_SUCCESS);
} else {
waitpid(childpid, &status, 0);
puts("in parent");
printf("\tparent pid = %d\n", getpid());
printf("\tparent ppid = %d\n", getppid());
printf("\tchild process exited with status %d \n", status);
}
exit(EXIT_SUCCESS);
}
如果程序是exit退出 WIFEXITED为真
if(WIFEXITED(status)){
fprintf(stdout,"child %d",WEXITSTATUS(status));
}
sleep() 函数将程序挂起一段时间
unsigned int sleep(unsigned int sleep_time);
int pause(void) 让调用函数休眠,直到该进程收到一个信号