Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1204834
  • 博文数量: 252
  • 博客积分: 5421
  • 博客等级: 大校
  • 技术积分: 2418
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-17 12:59
文章分类

全部博文(252)

文章存档

2017年(3)

2016年(18)

2015年(31)

2014年(18)

2013年(7)

2012年(8)

2011年(12)

2010年(30)

2009年(32)

2008年(57)

2007年(36)

分类: C/C++

2010-12-24 00:02:33

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


阅读(2270) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-26 17:39:49

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com