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

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

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

时间:2015-01-09 15:19:04 作者:qipeng 来源:系统之家 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()配合使用,否则起不到进程间通信的作用。

发表评论

0

没有更多评论了

评论就这些咯,让大家也知道你的独特见解

立即评论

以上留言仅代表用户个人观点,不代表系统之家立场

其他版本软件

热门教程

人气教程排行

Linux系统推荐

官方交流群 软件收录