zoukankan      html  css  js  c++  java
  • Linux pipe函数

    1. 函数说明

    pipe(建立管道):
    1) 头文件 #include<unistd.h>
    2) 定义函数: int pipe(int filedes[2]);
    3) 函数说明: pipe()会建立管道,并将文件描写叙述词由參数filedes数组返回。
                  filedes[0]为管道里的读取端
                  filedes[1]则为管道的写入端。
    4) 返回值:  若成功则返回零,否则返回-1,错误原因存于errno中。

        错误代码:
             EMFILE 进程已用完文件描写叙述词最大量
             ENFILE 系统已无文件描写叙述词可用。
             EFAULT 參数 filedes 数组地址不合法。

    2. 举例

    #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.
    " );
            char s[] = "Hello world , this is write by pipe.
    ";
            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.
    " );
            read( filedes[0], buf, sizeof(buf) );
            printf( "%s
    ", 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.

    当管道中的数据被读取后,管道为空。一个随后的read()调用将默认的被堵塞,等待某些数据写入。

    若须要设置为非堵塞,则可做例如以下设置:

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

     

  • 相关阅读:
    MyMacro
    CConfigXmlFile02
    “十步一杀” 干掉你的职场压力
    只有聪明人才悟到:通向成功的饥饿法则
    高层管理者应具备什么样的特点? (转)
    两个小故事,告诉你不可不知的成功密码
    中秋望月
    锦里中秋有感
    支招:如何增强创业信心,克服创业恐惧?
    创业者必看:创业得出的10条血泪经验
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4199436.html
Copyright © 2011-2022 走看看