菜鸟问个关于fork的问题

sicofield 2013-09-09 03:38:33
下面是一段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
...全文
121 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
BT_Dana 2013-09-10
  • 打赏
  • 举报
回复
http://www.slyar.com/blog/c-operator-priority.html 赋值操作符的优先级几乎是最低的了, 仅大于逗号运算符.
再改变 2013-09-09
  • 打赏
  • 举报
回复
Coggle阿水 2013-09-09
  • 打赏
  • 举报
回复
同上,你写漏了括号
qiyu1988 2013-09-09
  • 打赏
  • 举报
回复
if(pid=fork()<0)少了() if((pid=fork())<0)

4,441

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧