来源:http://hohahohayo.blog.163.com/blog/static/120816010200971210230362/ide
wait(等待子进程中断或结束)
表头文件
#include<sys/types.h>
#include<sys/wait.h>
定义函数 pid_t wait (int * status);
函数说明:
wait()会暂时中止目前进程的执行,直到有信号来到或子进程结束。函数
/****** * waitpid.c - Simple wait usage *********/ #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 ( -1 == childpid ) { perror( "fork()" ); exit( EXIT_FAILURE ); } else if ( 0 == childpid ) { 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); }
[root@localhost src]# gcc waitpid.c
[root@localhost src]# ./a.out
In child process
child pid = 4469
child ppid = 4468
in parent
parent pid = 4468
parent ppid = 4379
child process exited with status 0
[root@localhost src]#
若是将上面“waitpid( childpid, &status, 0 );”行注释掉,程序执行效果以下:
[root@localhost src]# ./a.out
In child process
in parent
parent pid = 4481
parent ppid = 4379
child process exited with status 1331234400
[root@localhost src]# child pid = 4482
child ppid = 1
子进程尚未退出,父进程已经退出了。spa