网络安全参考 | UNIX参考 | GPS参考 | 无线参考 | 在线手册 | OSBUG.ORG | SUNNY-NETWORK.COM
天线制作 GPS 地标
网站地图 RSS订阅
高级搜索 收藏本站
Home | 业界动态 | Open source | GNU | Linux | BSD | Solaris | AIX | HP-UX | IRIX | Mac OS X | Minix | Tru64 | SCO UNIX | Network | Security | X-Window | Database | 应用服务 | Programming | 经典著作 | 永远的纪念 | 杂项
 当前位置: Home > Linux > 程序设计 > 进程间通讯 > 文章  
Linux环境进程间通信: 管道及有名管道
文章来源: IBM Developerworks 文章作者: 郑彦兴 发布时间: 2002-12-11   字体: [ ]  
 
  int cmd;
 
  memset(r_buf,0,sizeof(r_buf));
  if(pipe(pipe_fd)<0)
  {
    printf("pipe create error\n");
    return -1;
  }
 
  if((pid=fork())==0)
  {
    close(pipe_fd[0]);
    close(pipe_fd[1]);
    sleep(10);
    exit();
  }
  else if(pid>0)
  {
    sleep(1);  //等待子进程完成关闭读端的操作
    close(pipe_fd[0]);//write
    w_buf="111";
    if((writenum=write(pipe_fd[1],w_buf,4))==-1)
      printf("write to pipe error\n");
    else
      printf("the bytes write to pipe is %d \n", writenum);
   
    close(pipe_fd[1]);
  }
}

  则输出结果为: Broken pipe,原因就是该管道以及它的所有fork()产物的读端都已经被关闭。如果在父进程中保留读端,即在写完pipe后,再关闭父进程的读端,也会正常写入pipe,读者可自己验证一下该结论。因此,在向管道写入数据时,至少应该存在某一个进程,其中管道读端没有被关闭,否则就会出现上述错误(管道断裂,进程收到了SIGPIPE信号,默认动作是进程终止)

  对管道的写规则的验证2:linux不保证写管道的原子性验证

#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
 
main(int argc,char**argv)
{
  int pipe_fd[2];
  pid_t pid;
  char r_buf[4096];
  char w_buf[4096*2];
  int writenum;
  int rnum;
  memset(r_buf,0,sizeof(r_buf));
  if(pipe(pipe_fd)<0)
  {
    printf("pipe create error\n");
    return -1;
  }
 
  if((pid=fork())==0)
  {
    close(pipe_fd[1]);
    while(1)
 
推荐文章
·Linux环境进程间通信(二): 信号(
·深刻理解Linux进程间通信(IPC)
 
 
↑返回顶部   打印本页   关闭窗口↓  

Google
 
Web oldhand.org unixreference.net meshmea.org
相关分类
热点文章
·Linux环境进程间通信(二
·深刻理解Linux进程间通
相关文章
·深刻理解Linux进程间通
·Linux环境进程间通信(二
更多...
 
 

Copyright(c) 2001-2009 OLDHAND ORGANIZATION, All Rights reserved.
Power by DedeCms 织梦内容管理系统