变量的定义位置能阻塞read()么?。。。

xiaowai0219 2010-07-05 11:47:25
我看别人的帖子,发现的。其中有些输出是我加上去跟踪的,另外他的一些我觉得没用的东西我删去了。。。
问题见代码
原帖:http://topic.csdn.net/u/20100705/12/76d0ba52-d69a-4a63-8ed9-b69ee5133d51.html?seed=2002480615&r=66741590#r_66741590
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t pid;
int buf1,x,buf2;/*****************/

int fd[2];
pid=fork();
pipe(fd);
if(pid<0)
{
printf("error in fork!");
exit(0);
}
else if(pid==0)
{
buf1=getpid();
write(fd[1],(void*)buf1,sizeof(buf1));
close(fd[0]);
close(fd[1]);
x++;
printf("child:%d\n",getpid());
sleep(2);
}
else
{
printf("prarent before read\n");
read(fd[0],(void*)buf2,sizeof(buf2));/*阻塞处*/
/***************************************************
阻塞是根据输出判断的,能输出prarent before read,不能输出prarent before read则为阻塞。
int x,buf1,buf2; //阻塞
int buf1,x,buf2; //阻塞
int buf1,buf2,x; //不阻塞
原因何在?请指教。。。
*****************************************************/
printf("prarent before read\n");
close(fd[0]);
close(fd[1]);
printf("wait:%d\n",getpid());
wait(NULL);

}
printf("return:%d\n",getpid());
return 0;
}
...全文
87 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangzhifu 2010-07-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 nossiac 的回复:]

在父进程调用read前关闭fd[1]就可以达到你的目的。

这跟变量先后顺序没关系,是pipe本身的特点。
pipe是单向的,读端要关闭写,写端要关闭读,UNP卷2专门有讲。
[/Quote]

问题的关键就是这个
cceczjxy 2010-07-06
  • 打赏
  • 举报
回复

pid=fork();
pipe(fd);

先后循序颠倒了
gamblervip 2010-07-06
  • 打赏
  • 举报
回复
我没看明白,你那段阻塞的说明,但是,代码里fork后你使用了pipe,也就是说,父子进程分别创建了自己的管道,父进程实际上是无法打印出子进程管道里的东西的
xiaowai0219 2010-07-06
  • 打赏
  • 举报
回复
很是不明白,从没见过有这样的东西能扯到一起去的。。。
xiaowai0219 2010-07-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 nossiac 的回复:]
在父进程调用read前关闭fd[1]就可以达到你的目的。

这跟变量先后顺序没关系,是pipe本身的特点。
pipe是单向的,读端要关闭写,写端要关闭读,UNP卷2专门有讲。
[/Quote]
这是个原因,在read前关闭写的话,能正常运行
但是如上面代码所示,若读前部关闭写的话,就有上述定义引起的问题了。
很是不明白。。。
其实那个x就是个没使用的变量,x++是我用来安慰编译器的。
nossiac 2010-07-06
  • 打赏
  • 举报
回复
在父进程调用read前关闭fd[1]就可以达到你的目的。

这跟变量先后顺序没关系,是pipe本身的特点。
pipe是单向的,读端要关闭写,写端要关闭读,UNP卷2专门有讲。

xiaowai0219 2010-07-05
  • 打赏
  • 举报
回复
gcc 3.4.4

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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