父进程获取子进程退出状态(1)
2010-12-23 02:39
405 查看
main.cpp:
child.cpp:(g++ child.cpp -o child)
#include <unistd.h> #include <iostream> #include <sys/wait.h> #include <signal.h> #include <stdlib.h> using namespace std; void child_over_callback(int); void parent_sig_handler(int sig) { cout << "parent catch signal:" << sig << endl; if (sig == SIGCHLD) { int status; pid_t pid; pid = wait(&status); cout << "parent's child - pid:"<< pid << ",status:" << status << endl; if (WIFEXITED(status)) { cout << ">> child exited, exit code=" << WEXITSTATUS(status) << endl; child_over_callback(sig); } else if (WIFSIGNALED(status)) { cout << ">> child killed (signal " << WTERMSIG(status) << ")/n"; } else if (WIFSTOPPED(status)) { cout << ">> child stopped (signal " << WSTOPSIG(status) << ")/n"; #ifdef WIFCONTINUED } else if (WIFCONTINUED(status)) { cout << ">> child continued/n"; #endif } else { cout << ">> Unexpected status (" << status << ")/n"; } } else { cout << ">> child exec error/n"; exit(1); } } void child_over_callback(int sig) { cout << "parent signal(" << sig << ") callback/n"; } int main() { int ret; ret = fork(); if (ret > 0) { cout << "parent start/n"; struct sigaction sa, sa2, oldsa, oldsa2; sa.sa_handler = parent_sig_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, &oldsa) == -1) { cout << "parent sigaction(SIGCHLD) error/n"; } sa2.sa_handler = parent_sig_handler; sigemptyset(&sa2.sa_mask); sa2.sa_flags = SA_RESTART; if (sigaction(SIGUSR1, &sa2, &oldsa2) == -1) { cout << "parent sigaction(SIGUSR1) error/n"; } cout << "parent sleep(40)/n"; sleep(40); } else if (ret == 0) { pid_t ppid = getppid(); cout << "child start/n"; cout << "child ppid:" << ppid << endl; cout << "child pid:" << getpid() << endl; cout << "child exec/n"; if (execl ("./child", "child", (char *)0) < 0) { cout << "child exec error/n"; kill(ppid, SIGUSR1); } } else { cout << "fork error/n"; } return 0; }
child.cpp:(g++ child.cpp -o child)
#include <unistd.h> #include <iostream> using namespace std; int main() { cout << "child exec start/n"; cout << "child exec ppid:" << getppid() << endl; cout << "child exec pid:" << getpid() << endl; sleep(30); return 0; }
相关文章推荐
- 父进程获取子进程退出状态(2)
- shell同时启多个进程,并等待所有子进程结束,再做接下来的操作,最好能获取每个子进程的退出状态
- wait获取子进程退出状态 WIFEXITED和WIFSIGNALED用法
- wait获取子进程退出状态 WIFEXITED和WIFSIGNALED用法
- linux c 父进程判断子进程退出状态
- linux c 唤醒进程 获取子进程结束状态
- UNIX环境编程学习笔记(21)——进程管理之获取进程终止状态的 wait 和 waitpid 函数
- 子进程system_service创建后while一直判断子进程状态是否died,如果会则zygote也kill自己
- Linux并发(子进程退出状态的处理)
- 主进程被杀死时,如何保证子进程同时退出,而不变为孤儿进程(二)
- 进程管理:通过父进程ID获取子进程ID
- 死亡通知与进程异常退出;ANR与进程重启后状态跟之前不对
- C++ 获取当前进程运行目录(visual studio 调试状态下)
- 子进程终止父进程捕捉子进程退出信号
- c# process 获取进程退出码
- 如何获取进程的终止状态
- 获取进程号并赋值判断进程状态
- 进程fork()两次---解决一个进程不必等待子进程终止,也不希望子进程处于僵死状态(一般是服务器进程fork())
- 获取子进程的退出码
- Linux 父进程如何获取子进程返回值?parent get child process return value,fork,wait,wait_pid