Chinaunix首页 | 论坛 | 博客
  • 博客访问: 416458
  • 博文数量: 68
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 671
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-11 13:36
文章分类

全部博文(68)

文章存档

2010年(14)

2009年(7)

2008年(47)

我的朋友

分类: LINUX

2008-08-28 13:26:24

pipe(建立管道)

表头文件 #include
定义函数 int pipe(int filedes[2]);
函数说明
    pipe()会建立管道,并将文件描述词由参数 filedes 数组返回。
    filedes[0]为管道里的读取端,所以pipe用read调用的
    filedes[1]则为管道的写入端。
    
返回值:  若成功则返回零,否则返回-1,错误原因存于 errno 中。
错误代码:
    EMFILE 进程已用完文件描述词最大量
    ENFILE 系统已无文件描述词可用。
    EFAULT 参数 filedes 数组地址不合法。

#include
#include

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.
阅读(3159) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~