pipe()函数的使用

一.http://jesserei.blog.163.com/blog/static/1214116892010329115649264/

pipe(建立管道)

表头文件 #include<unistd.h>

定义函数 int pipe(int filedes[2]);

函数说明

    pipe()会建立管道,并将文件描述词由参数 filedes 数组返回。

    filedes[0]为管道里的读取端,所以pipe用read调用的

    filedes[1]则为管道的写入端。

   

返回值: 若成功则返回零,否则返回-1,错误原因存于 errno 中。

错误代码:

    EMFILE 进程已用完文件描述词最大量

    ENFILE 系统已无文件描述词可用。

    EFAULT 参数 filedes 数组地址不合法。

#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.


fork之后,操作系统会复制一个与父进程完全相同的子进程,虽说是父子关系,但是在操作系统 看来,他们更像兄弟关系,这2个进程共享代码空间,但是数据空间是互相独立的,子进程数据空间中的内容是父进程的完整拷贝,指令指针也完全相同,但只有一 点不同,如果fork成功,子进程中fork的返回值是0,父进程中fork的返回值是子进程的进程号,如果fork不成功,父进程会返回错误。 
可以这样想象,2个进程一直同时运行,而且步调一致,在fork之后,他们分别作不同的工作,也就是分岔了。这也是fork为什么叫fork的原因。 
至于那一个最先运行,可能与操作系统有关,而且这个问题在实际应用中并不重要,如果需要父子进程协同,可以通过原语的办法解决。


#include <unistd.h>;

#include <sys/types.h>;



main ()

{

        pid_t pid;

        pid=fork();



        if (pid < 0)

                printf("error in fork!");

        else if (pid == 0)

                printf("i am the child process, my process id is %d\n",getpid());

        else

                printf("i am the parent process, my process id is %d\n",getpid());

}
结果是 
[root@localhost c]# ./a.out 
i am the child process, my process id is 4286 

i am the parent process, my process id is 4285


二.http://www.cnblogs.com/kunhu/p/3608109.html

管道是一种把两个进程之间的标准输入和标准输出连接起来的机制,从而提供一种让多个进程间通信的方法,当进程创建管道时,每次

都需要提供两个文件描述符来操作管道。其中一个对管道进行写操作,另一个对管道进行读操作。对管道的读写与一般的IO系统函数一

致,使用write()函数写入数据,使用read()读出数据。

#include<unistd.h>

int pipe(int filedes[2]);

返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道。

必须在fork()中调用pipe(),否则子进程不会继承文件描述符。两个进程不共享祖先进程,就不能使用pipe。但是可以使用命名管道。

 

当管道进行写入操作的时候,如果写入的数据小于128K则是非原子的,如果大于128K字节,缓冲区的数据将被连续地写入

管道,直到全部数据写完为止,如果没有进程读取数据,则将一直阻塞,如下:

在上例程序中,子进程一次性写入128K数据,当父进程将全部数据读取完毕的时候,子进程的write()函数才结束阻塞并且

返回写入信息。

命名管道FIFO

管道最大的劣势就是没有名字,只能用于有一个共同祖先进程的各个进程之间。FIFO代表先进先出,单它是一个单向数据流,也就是半双工,和

管道不同的是:每个FIFO都有一个路径与之关联,从而允许无亲缘关系的进程访问。  

        #include <sys/types.h>

        #include <sys/stat.h>

      int mkfifo(const char *pathname, mode_t mode);
     这里pathname是路径名,mode是sys/stat.h里面定义的创建文件的权限.

以下示例程序来自:http://blog.chinaunix.net/uid-20498361-id-1940238.html

  有亲缘关系进程间的fifo的例子

/*
 * 有亲缘关系的进程间的fifo的使用
 * fifo 使用的简单例子
 */

#include "../all.h"

#define FIFO_PATH "/tmp/hover_fifo"


void 
do_sig(int signo)
{
    if (signo == SIGCHLD)
        while (waitpid(-1, NULL, WNOHANG) > 0)
            ;
}


int
main(void)
{
    int ret;
    int fdr, fdw;
    pid_t pid;

    char words[10] = "123456789";
    char buf[10] = {'\0'};    
    
    // 创建它,若存在则不算是错误,
    // 若想修改其属性需要先打开得到fd,然后用fcntl来获取属性,然后设置属性.

    if (((ret = mkfifo(FIFO_PATH, FILE_MODE)) == -1) 

                     && (errno != EEXIST))
        perr_exit("mkfifo()");
    fprintf(stderr, "fifo : %s created successfully!\n", FIFO_PATH);

    signal(SIGCHLD, do_sig);

    pid = fork();
    if (pid == 0) { // child

        if ((fdr = open(FIFO_PATH, O_WRONLY)) < 0) // 打开fifo用来写
            perr_exit("open()");
        sleep(2);

        // 写入数据
        if (write(fdr, words, sizeof(words)) != sizeof(words)) 
            perr_exit("write");
        fprintf(stderr, "child write : %s\n", words);
        close(fdw);
    } else if (pid > 0) { // parent

        if ((fdr = open(FIFO_PATH, O_RDONLY)) < 0) // 打开fifo用来读

            perr_exit("open()");

        fprintf(stderr, "I father read, waiting for child ...\n");
        if (read(fdr, buf, 9) != 9) //读数据
            perr_exit("read");

        fprintf(stderr, "father get buf : %s\n", buf);
        close(fdr);
    }
    // 到这里fifo管道并没有被删除,必须手动调用函数unlink或remove删除.

    return 0;    
}


从例子上可以看出使用fifo时需要注意:
*fifo管道是先调用mkfifo创建,然后再用open打开得到fd来使用.
*在打开fifo时要注意,它是半双工的的,一般不能使用O_RDWR打开,而只能用只读或只写打开.

   fifo可以用在非亲缘关系的进程间,而它的真正用途是在服务器和客户端之间. 由于它是半双工的所以,如果要进行客户端和服务器双方的通信的话,

每个方向都必须建立两个管道,一个用于读,一个用于写.

下面是一个服务器,对多个客户端的fifo的例子:

server 端的例子:



/*
 * FIFO server
 */

#include "all.h"

int
main(void)
{
    int fdw, fdw2;
    int fdr;
    char clt_path[PATH_LEN] = {'\0'};
    char buf[MAX_LINE] = {'\0'};
    char *p;
    int n;
    
    if (mkfifo(FIFO_SVR, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");    
    if ((fdr = open(FIFO_SVR, O_RDONLY)) < 0)    
        perr_exit("open()");
    /* 
     * 根据fifo的创建规则, 若从一个空管道或fifo读, 

     * 而在读之前管道或fifo有打开来写的操作, 那么读操作将会阻塞 
     * 直到管道或fifo不打开来读, 或管道或fifo中有数据为止. 

     *

     * 这里,我们的fifo本来是打开用来读的,但是为了,read不返回0,

     * 让每次client端读完都阻塞在fifo上,我们又打开一次来读.
     * 见unpv2 charper 4.7
     */
    if ((fdw2 = open(FIFO_SVR, O_WRONLY)) < 0)    
        fprintf(stderr, "open()");
    
    while (1) {
        /* read client fifo path from FIFO_SVR */

     /* 这里由于FIFO_SVR有打开来写的操作,所以当管道没有数据时, 

      * read会阻塞,而不是返回0. 

      */
        if (read(fdr, clt_path, PATH_LEN) < 0) {
            fprintf(stderr, "read fifo client path error : %s\n", strerror(errno));    
            break;
        }
        if ((p = strstr(clt_path, "\r\n")) == NULL) {
            fprintf(stderr, "clt_path error: %s\n", clt_path);
            break;
        }
        *p = '\0';
        DBG("clt_path", clt_path);
        if (access(clt_path, W_OK) == -1) { // client fifo ok, but no permission

            perror("access()");    
            continue;
        }
        /* open client fifo for write */
        if ((fdw = open(clt_path, O_WRONLY)) < 0) {
            perror("open()");    
            continue;
        }
        if ((n = read(fdr, buf, WORDS_LEN)) > 0) { /* read server words is ok */
            printf("server read words : %s\n", buf);
            buf[n] = '\0';
            write(fdw, buf, strlen(buf));    
        }
    }
    
    close(fdw);    
    unlink(FIFO_SVR);
    exit(0);
}


客户端的例子:


 

/*
 * Fifo client
 *
 */
#include "all.h"



int
main(void)
{
    int fdr, fdw;
    pid_t pid;    
    char clt_path[PATH_LEN] = {'\0'};
    char buf[MAX_LINE] = {'\0'};
    char buf_path[MAX_LINE] = {'\0'};
    
    snprintf(clt_path, PATH_LEN, FIFO_CLT_FMT, (long)getpid());        
    DBG("clt_path1 = ", clt_path);
    snprintf(buf_path, PATH_LEN, "%s\r\n", clt_path);

    if (mkfifo(clt_path, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");

    /* client open clt_path for read
     * open server for write 
       */
    if ((fdw = open(FIFO_SVR, O_WRONLY)) < 0) 
        perr_exit("open()");
    
    /* write my fifo path to server */    
    if (write(fdw, buf_path, PATH_LEN) != PATH_LEN)        
        perr_exit("write()");
    if (write(fdw, WORDS, WORDS_LEN) < 0)    /* write words to fifo server */
        perr_exit("error");

    if ((fdr = open(clt_path, O_RDONLY)) < 0)    
        perr_exit("open()");
    if (read(fdr, buf, WORDS_LEN) > 0) {     /* read reply from fifo server */
        buf[WORDS_LEN] = '\0';
        printf("server said : %s\n", buf);
    }
    
    close(fdr);
    unlink(clt_path);
    
    exit(0);
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值