/a.cpp
#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 = %dn", getpid());
printf("tchild ppid = %dn", getppid());
exit(EXIT_SUCCESS);
}
else
{
waitpid( childpid, &status, 0);
puts( "in parent" );
printf( "tparent pid = %dn", getpid() );
printf( "tparent ppid = %dn", getppid() );
printf( "tchild process exited with status %d n", status);
}
exit(EXIT_SUCCESS);
}
执行结果为:./a.o
In child process
child pid = 4469
child ppid = 4468
in parent
parent pid = 4468
parent ppid = 4379
child process exited with status 0
如果将上面“waitpid( childpid,&status, 0 );”行注释掉,程序执行效果如下:./a.o
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
子进程还没有退出,父进程已经退出了。