免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1569 | 回复: 4
打印 上一主题 下一主题

请教进程的一些问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-07-20 19:44 |只看该作者 |倒序浏览
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
void h_exit(int status);
int main(void)
{
    pid_t pid;
    int status;
    if((pid=fork())<0)
    {
        printf("fork error!\n");
        exit(0);
    }
    else if(pid==0)
        exit(7);
    if(wait(&status)!=pid)
    {
        printf("wait error!\n");
        exit(0);
    }
    h_exit(status);

if((pid=fork())<0)
    {
        printf("fork error!\n");
        exit(0);
    }
    else if(pid==0)
        exit(1);
    if(wait(&status)!=pid)
    {
        printf("wait error!\n");
        exit(0);
    }
    h_exit(status);


    if((pid=fork())<0)
    {
        printf("fork error!\n");
        exit(0);
    }
    else if(pid==0)
    if(wait(&status)!=pid)
    {
         printf("wait error!\n");
        exit(0);
    }
    h_exit(status);
    exit(0);
}
void h_exit(int status)
{
    if(WIFEXITED(status))
        printf("normal termination,exit status=%d. \n", WEXITSTATUS(status));
    else if(WIFSIGNALED(status))
        printf("abnormal termination,exit status=%d. \n", WTERMSIG(status));
}


输出为何是:
normal termination,exit status=7.
normal termination,exit status=1.
wait error!
normal termination,exit status=1.

理论上应该是才对:
normal termination,exit status=7.
normal termination,exit status=1.
wait error!
normal termination,exit status=0.

子进程进入else if(pid==0)    if(wait(&status)!=pid)后 退出时应该返回0才对,为何父进程最后获取1

论坛徽章:
0
2 [报告]
发表于 2010-07-20 23:23 |只看该作者
你难道没有注意到“wait error!”

论坛徽章:
0
3 [报告]
发表于 2010-07-20 23:25 |只看该作者
有这句东西怎样了,子程序最后还是exit(0)

论坛徽章:
0
4 [报告]
发表于 2010-07-20 23:40 |只看该作者
但是wait 的返回值就变了

论坛徽章:
0
5 [报告]
发表于 2010-07-21 00:37 |只看该作者
这个算是解决了。但最后子进程在等待的时候,顺序是先执行完主进程,等主进程结束后然后才轮到子进程。这样最后一次输出应该是:
normal termination,exit status=0.
wait error!

但程序却是:
wait error!
normal termination,exit status=0.

不同编译器版本会有不同的顺序嘛?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP