双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

菜鸟问个关于fork的问题

sicofield sicofield 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面是一段APUE上管道的示例程序,中间自己添加了一些printf看看程序的运行流程。结果发现子进程的代码段执行了两次而父进程代码段没有执行!!尽然会有这种事!!!实在搞不懂错在哪里。
#include <stdio.h>
#include <unistd.h>
#define BUFSIZE 100
int main()
{
int n;
int fd[2];
pid_t pid;
char buf[BUFSIZE];
if(pipe(fd)<0)
printf("pipe errorn");
if(pid=fork()<0)
printf("fork errorn");
if (pid>0)/*parent*/
{
close(fd[0]);
printf("this is parent process");
write(fd[1],"Hello world",12);
}
if(pid==0) /*child*/
{
//sleep(1);
printf("this is child process");
close(fd[1]);
n=read(fd[0],buf,BUFSIZE);
write(STDOUT_FILENO,buf,n);
}
return 0;
}

这段程序在我的机器上运行结果为:
this is child process
this is child process
...全文
评论 4
收藏 已收藏
分享
返回顶部
sicofield
Linux_Kernel 4,469 成员 17,458 内容