Linux建立pipe管道函数的方法(2) - win系统之家

win系统之家 - 系统光盘下载网站!

当前位置:win系统之家 > 系统教程 > Linux建立pipe管道函数

Linux建立pipe管道函数的方法(2)

时间:2015-01-09 15:19:04 作者:qipeng 来源:win系统之家 1. 扫描二维码随时看资讯 2. 请使用手机浏览器访问: https://m.xitongzhijia.net/xtjc/20150109/34461.html 手机查看 评论

  2. 举例

  [cpp] view plaincopy

  #include 《unistd.h》

  #include 《stdio.h》

  int main( void )

  {

  int filedes[2];

  char buf[80];

  pid_t pid;

  pipe( filedes );

  pid=fork();

  if (pid 》 0)

  {

  printf( “This is in the father process,here write a string to the pipe./n” );

  char s[] = “Hello world , this is write by pipe./n”;

  write( filedes[1], s, sizeof(s) );

  close( filedes[0] );

  close( filedes[1] );

  }

  else if(pid == 0)

  {

  printf( “This is in the child process,here read a string from the pipe./n” );

  read( filedes[0], buf, sizeof(buf) );

  printf( “%s/n”, buf );

  close( filedes[0] );

  close( filedes[1] );

  }

  waitpid( pid, NULL, 0 );

  return 0;

  }

  运行结果:

  [root@localhost src]# gcc pipe.c

  [root@localhost src]# 。/a.out

  This is in the child process,here read a string from the pipe.

  This is in the father process,here write a string to the pipe.

  Hello world , this is write by pipe.

  当管道中的数据被读取后,管道为空。一个随后的read()调用将默认的被阻塞,等待某些数据写入。

  若需要设置为非阻塞,则可做如下设置:

  fcntl(filedes[0], F_SETFL, O_NONBLOCK);

  fcntl(filedes[1], F_SETFL, O_NONBLOCK);

  上面就是Linux建立pipe管道函数的方法介绍了,需要注意的是,pipe函数需要和fork()配合使用,否则起不到进程间通信的作用。

其他版本软件

热门教程

人气教程排行

Linux系统推荐

本站发布的系统仅为个人学习测试使用,请在下载后24小时内删除,不得用于任何商业用途,否则后果自负,请支持购买微软正版系统!

如侵犯到您的权益,请及时通知我们,我们会及时处理,对系统之家有任何投诉或建议,请与管理员联系. QQ:346231061

Copyright2023 win系统之家(chunjing.598888.xyz) 版权所有 沪ICP备2021023961号-3