父进程获取子进程退出状态(1)

进程间通信案例

main.cpp:

#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; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值