pipe(建立管道)
表頭文件 #include<unistd.h>
定義函數(shù) int pipe(int filedes[2]);
函數(shù)說明
pipe()會建立管道,并將文件描述詞由參數(shù) filedes 數(shù)組返回。
filedes[0]為管道里的讀取端,所以pipe用read調(diào)用的
filedes[1]則為管道的寫入端。
返回值: 若成功則返回零,否則返回-1,錯誤原因存于 errno 中。
錯誤代碼:
EMFILE 進(jìn)程已用完文件描述詞最大量
ENFILE 系統(tǒng)已無文件描述詞可用。
EFAULT 參數(shù) filedes 數(shù)組地址不合法。
#include <unistd.h>
#include <stdio.h>
int main( void )
{
int filedes[2];
char buf[80];
pid_t pid;
pipe( filedes );
if ( (pid=fork()) > 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
{
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.
posted on 2010-06-14 18:19
老馬驛站 閱讀(2751)
評論(0) 編輯 收藏 引用 所屬分類:
c++ 、
linux