您的位置:首页 > 其它

等待子进程

2012-07-01 10:03 155 查看
#include <sys/types.h>

#include <sys/wait.h>

#include <unistd.h>

#include <stdio.h>

int main()

{

pid_t pid;

char *message;

int n;

int exit_code;

printf("fork program starting\n");

pid=fork();

switch(pid)

{

case -1:

perror("fork failed");

exit(1);

case 0:

message="this is the child";

n=5;

exit_code=37;

break;

default:

message="this is the parent";

n=3;

exit_code=0;

break;

}

for(;n>0;n--)

{

puts(message);

sleep(1);

}

if(pid!=0)

{

int stat_va;

pid_t child_pid;

child_pid=wait(&stat_va);

printf("child has finished:PID=%d\n",child_pid);

if(WIFEXITED(stat_va))

printf("child exited with the code %d\n",WEXITSTATUS(stat_va));

else

printf("child terminated abnormally\n");

}

exit(exit_code);

}

如果子进程正常结束,则WIFEXITED(stat_va)取一个非0值 如果WIFEXITED(stat_va)非0,则WEXITSTATUS(stat_va)返回子进程的退出码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: