Chinaunix首页 | 论坛 | 博客
  • 博客访问: 154609
  • 博文数量: 41
  • 博客积分: 1531
  • 博客等级: 上尉
  • 技术积分: 436
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 22:17
文章分类

全部博文(41)

文章存档

2013年(2)

2012年(1)

2011年(13)

2010年(25)

我的朋友

分类: C/C++

2010-07-02 16:25:40

pipe(建立管道)

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

#include
#include
#include

int main( void )
{
    int filedes[2];
    char buf[80];
    char s[] = "Hello world , this is write by pipe.\n";
       
    pid_t pid;
  
    pipe( filedes );
  
    if ( (pid=fork()) > 0 )
    {
        printf( "This is in the father process,here write a string to the 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, strlen(s)/2 );
        printf( "%s\n", buf );
        read( filedes[0], buf, strlen(s)/2 );
        printf( "%s\n", buf );
        close( filedes[0] );
        close( filedes[1] );
    }
  
    waitpid( pid, NULL, 0 );
  
    return 0;
}

[root@localhost linuxprogram]# ./pipe
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.

测试此函数时必须注意写到pipe中的字节数与读出的字节数的关系,pipe是先入先出的。
阅读(1044) | 评论(0) | 转发(0) |
0

上一篇:perror 函数使用

下一篇:NAS 相关

给主人留下些什么吧!~~