免费注册 查看新帖 |

Chinaunix

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

[C] 弱弱地问一个创建子进程的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-10-14 12:37 |只看该作者 |倒序浏览
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<math.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>

int main(){
        pid_t child;
        int status;
        printf("This will demostrate how to get child status\n");
        if((child=fork())==-1){
                printf("Fork Error :%s\n",strerror(errno));
                exit(1);
        }
        else if(child==0){ //不懂,我进行程序单步调试的时候,child总是不等于0的,可为什么这下面的语句能够输出。
                int i;
                printf("I am the  child: %ld\n",getpid());
                for(i=0;i<1000000;i++)
                        sin(i);
                i=5;
                printf("I exit with %d\n",i);
                exit(i);
        }
        while(((child=wait(&status))==-1)&(errno==EINTR));
        if(child==-1)
                printf("Wait Error: %s\n",strerror(errno));
        else if(!status)
                printf("Child %ld terminated normally return status is zero\n",child);
        else if(WIFEXITED(status))
                printf("Child %ld terminated normally return status is %d\n",
                        child,WEXITSTATUS(status));
        else if(WIFSIGNALED(status))
                printf("Child %ld terminated due to signal %d znot caught\n",
                        child,WTERMSIG(status));
}



else if(child==0){ //不懂,我进行程序单步调试的时候,child总是不等于0的,可为什么这下面的语句能够输出。

论坛徽章:
0
2 [报告]
发表于 2009-10-14 12:47 |只看该作者
fork调用成功,会返回两个值。

== 0,表示的是子进程。
> 0,表示的是父进程。

论坛徽章:
0
3 [报告]
发表于 2009-10-14 13:58 |只看该作者
确实有点儿麻烦,gdb继续调试父进程,没有理会子进程。

论坛徽章:
0
4 [报告]
发表于 2009-10-14 14:21 |只看该作者

回复 #2 naihe2010 的帖子

能否说说程序运行的流程呢,先谢谢了

论坛徽章:
0
5 [报告]
发表于 2009-10-14 14:22 |只看该作者

回复 #3 bert1984 的帖子

是的,调试的时候,直接就过去了

论坛徽章:
0
6 [报告]
发表于 2009-10-14 14:42 |只看该作者
那是子进程输出的

论坛徽章:
0
7 [报告]
发表于 2009-10-14 16:54 |只看该作者
调试子进程:
在子进程开始运行的地方让他等待,然后attach到这个进程

论坛徽章:
2
15-16赛季CBA联赛之四川
日期:2016-04-23 14:25:46操作系统版块每日发帖之星
日期:2016-05-09 06:20:00
8 [报告]
发表于 2009-10-14 17:58 |只看该作者

回复 #7 fera 的帖子

gdb 中要跟进去子进程,需设置set follow-fork-mode child

论坛徽章:
0
9 [报告]
发表于 2009-10-14 21:04 |只看该作者
感谢各位热心的帮助,特别感谢jeasun
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP