來源: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