linux pipe无法write!!!!!

超gogo 2012-02-25 09:30:49

#include<unistd.h>
#include<sys/types.h>
#include<iostream>
#include<string.h>
int main(int argc,char* argv[])
{
int command_pipe[2];
pid_t pid;
pid = fork();
char command_string[255];
if(pipe(command_pipe) < 0)
std::cerr<<"pipe failed"<<std::endl;
if(pid<0)
std::cerr<<"fork failed!"<<std::endl;
if(pid == 0)
{
char ch[255] = {'\0'};
close(command_pipe[1]);
int n=read(command_pipe[0],ch,255);
std::cout<<"child read:"<<n<<std::endl;
std::cout<<ch<<std::endl;

}
else
if(pid >0)
{
close(command_pipe[0]);
char m[255];
strcpy(m,"111");
if(-1!= write(command_pipe[1],m,4))
std::cout<<"write success"<<std::endl;
else
std::cout<<"write fail"<<std::endl;
close(command_pipe[1]);
}
return 0;
}





上面代码无法实现管道通信。
输出:
child read :0

因为write句子写了if else 所以 write success和write fail至少有一个会输出,但实际上二者都未输出
请问是为什么呢?
如何解决?谢谢
...全文
176 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2012-02-26
  • 打赏
  • 举报
回复
你的代码父子进程各自创建了各自的pipe.

然后子进程关闭自己管道的写, 进行读是可行的.
但是父进程会出错,因为关闭了读,写管道是不行的哦,man write看一下帮助把.

错误就是fork和pipe配合的问题, 应该先pipe, 然后fork, 这样子进程就继承了pipe的fd
超gogo 2012-02-26
  • 打赏
  • 举报
回复
请会的朋友帮忙啊,谢谢
超gogo 2012-02-25
  • 打赏
  • 举报
回复
write中的输出是随便写的,请大家不要纠结于为什么-1的时候输出了success这样的问题。
谢谢

23,125

社区成员

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

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