等待子进程
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)返回子进程的退出码
#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)返回子进程的退出码
相关文章推荐
- Linux信号(一)——子进程的异步等待方式
- 【Linux】子进程的异步等待方式
- Linux退出进程exit/_exit和等待子进程退出wait函数分析
- Linux父进程对于子进程的异步等待
- linux等待所有子进程的方法
- 子进程等待父进程退出及fork使用
- 父进程等待子进程退出
- 让wait等待所有子进程结束
- 进程等待及子进程异步等待方式
- linux c 等待所有子进程结束
- Linux下利用fork()创建子进程并使父进程等待子进程结束
- shell命令管道未读完阻塞了子进程,与等待其结束的父进程死"锁"。
- 带超时的等待子进程,timed_wait
- 父进程 等待子进程初始化后才使用子进程_waitforinputidle
- waitpid等待子进程收到STOP CONTINU信号,并且从terminal status看是什么信号引起的
- 父进程异步等待子进程
- 【Linux】子进程的异步等待方式
- Windows批处理 调用程序后 不等待子进程 父进程继续执行命令
- 进程fork()两次---解决一个进程不必等待子进程终止,也不希望子进程处于僵死状态(一般是服务器进程fork())
- Windows批处理 调用程序后 不等待子进程 父进程继续执行命令