Linux下的管道編程技術(4)
發表于:2013-03-06來源:開源黃頁作者:天狼星點擊數:
標簽:linux
14: if ( pipe( thePipe ) == 0 ) ...{ 15: 16: if (fork() == 0) ...{ 17: 18: ret = read( thePipe[0], buf, MAX_LINE ); 19: buf[ret] = 0; 20: printf( Child read %s\n, buf ); 21: 22: } else ...{ 23: 24: re

14: if ( pipe( thePipe ) == 0 ) ...{

15:

16: if (fork() == 0) ...{

17:

18: ret = read( thePipe[0], buf, MAX_LINE );

19: buf[ret] = 0;

20: printf( "Child read %s\n", buf );

21:

22: } else ...{

23:

24: ret = write( thePipe[1], testbuf, strlen(testbuf) );

25: ret = wait( NULL );

26:

27: }

28:

29: }

30:

31: return 0;

32: }
需要注意的是,在這個示例程序中我們沒有說明如何關閉管道,因為一旦進程結束,與管道有關的資源將被自動釋放。盡管如此,為了養成一種良好的編程習慣,最好利用close調用來關閉管道的描述符,如下所示:

ret = pipe( myPipe );

...

close( myPipe[0] );

close( myPipe[1] );
如果管道的寫入端關閉,但是還有進程嘗試從管道讀取的話,將被返回0,用來指出管道已不可用,并且應當關閉它。如果管道的讀出端關閉,但是還有進程嘗試向管道寫入的話,試圖寫入的進程將收到一個SIGPIPE信號,至于信號的具體處理則要視其信號處理程序而定了。
2.2 dup函數和dup2函數
dup和dup2也是兩個非常有用的調用,它們的作用都是用來復制一個文件的描述符。它們經常用來重定向進程的stdin、stdout和stderr。這兩個函數的原型如下所示:

#include

int dup( int oldfd );
原文轉自:http://yp.oss.org.cn/blog/show_resource.php?resource_id=598