系統(tǒng)之家 - 系統(tǒng)光盤下載網(wǎng)站!

當(dāng)前位置:系統(tǒng)之家 > 系統(tǒng)教程 > Linux建立pipe管道函數(shù)

Linux建立pipe管道函數(shù)的方法(2)

時(shí)間:2015-01-09 15:19:04 作者:qipeng 來(lái)源:系統(tǒng)之家 1. 掃描二維碼隨時(shí)看資訊 2. 請(qǐng)使用手機(jī)瀏覽器訪問(wèn): https://m.xitongzhijia.net/xtjc/20150109/34461.html 手機(jī)查看 評(píng)論

  2. 舉例

 。踓pp] 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;

  }

  運(yùn)行結(jié)果:

  [root@localhost src]# gcc pipe.c

 。踨oot@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.

  當(dāng)管道中的數(shù)據(jù)被讀取后,管道為空。一個(gè)隨后的read()調(diào)用將默認(rèn)的被阻塞,等待某些數(shù)據(jù)寫入。

  若需要設(shè)置為非阻塞,則可做如下設(shè)置:

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

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

  上面就是Linux建立pipe管道函數(shù)的方法介紹了,需要注意的是,pipe函數(shù)需要和fork()配合使用,否則起不到進(jìn)程間通信的作用。

標(biāo)簽 管道 pipe

發(fā)表評(píng)論

0

沒(méi)有更多評(píng)論了

評(píng)論就這些咯,讓大家也知道你的獨(dú)特見解

立即評(píng)論

以上留言僅代表用戶個(gè)人觀點(diǎn),不代表系統(tǒng)之家立場(chǎng)

其他版本軟件

熱門教程

人氣教程排行

Linux系統(tǒng)推薦

官方交流群 軟件收錄