文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>父进程获取子进程退出状态(2) -- 通过wait系统调用

父进程获取子进程退出状态(2) -- 通过wait系统调用

时间:2010-12-24  来源:flynetcn

main.cpp:

#include <unistd.h>
#include <iostream>
#include <sys/wait.h>
#include <stdlib.h>


using namespace std;


int main()
{
    int ret;
    ret = fork();
    if (ret > 0) {
        cout << "parent start\n";
        int status; pid_t pid;
        pid = wait(&status);
        if (pid != ret) {
            cout << "parent wait error(wait return pid:" << pid << ", fork return pid:" << ret << ")\n";
            exit(1);
        } else {
            cout << "parent wait return(pid:" << pid << ")\n";
        }
        cout << "parent's child end - pid:"<< pid << ", status:" << status << endl;
        if (WIFEXITED(status)) {
            cout << ">> child exited, exit code=" << WEXITSTATUS(status) << endl;
            if (WEXITSTATUS(status) == 1) {
                cout << ">> child exec error\n";
            }
        } else if (WIFSIGNALED(status)) {
            cout << ">> child killed (signal " << WTERMSIG(status) << ")\n";
#ifdef WCOREDUMP
        } else if (WCOREDUMP(status)) {
            cout << ">> child core file generated\n";
#endif
        } 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 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";
            exit(1);
        }
    } 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;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载