linux管道编程

ITlover00 2013-05-12

管道有自己的一套文件系统,它不映射到磁盘,而只是存在内存里。

每个一个管道都有一个缓冲空间,大小因系统而异。

ulimit -a | grep pipe

pipe size            (512 bytes, -p) 8

管道的读写支持block特性。

pipe的阻塞可以通过int fcntl(int fd, int cmd, ... /* arg */ )修改

匿名管道pipe

用于有公共祖先的进程间的通信

#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
    int pfd[2];
    if (pipe(pfd) == -1) {
        perror("pipe");
        exit(-1);
    }   

    pid_t pid = fork();
    if (pid == 0) { // child
        close(pfd[1]);
        sleep(10);
        // father is exit already, but the data it sent is there
        char rdbuf[1024];
        int len = read(pfd[0], rdbuf, sizeof(rdbuf));
        printf("child read %d\n", len);
        printf("%s\n", rdbuf);
        close(pfd[0]);
    } else if (pid > 0) { // father, self
        close(pfd[0]);
        int flag = fcntl(pfd[1], F_GETFL, 0); 
        flag |= O_NONBLOCK;
        if (fcntl(pfd[1], F_SETFL, flag) == -1) {
            perror("fcntl");
            exit(-1);
        }   
        char wrbuf[] = "hello pipe!";
        int len = write(pfd[1], wrbuf, sizeof(wrbuf));
        printf("father write %d\n", len);
        close(pfd[1]);
    } else {
        perror("fork");
    }   
    return 0;
}

命令管道fifo

用于任意进程间的通信

#define _OPEN_SYS
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int main() {
    char fn[]="temp.fifo";
    char out[20]="FIFO's are fun!", in[20];
    int rfd, wfd;

    if (mkfifo(fn, S_IRWXU) == -1) {
        if (errno == EEXIST) {
            perror("mkfifo wanning");
        } else {
            perror("mkfifo error");
            exit(-1);
        }   
    }   


    chmod(fn, 666); // give w permission to group and other

    // either O_RDONLY or O_WRONLY
    if ((rfd = open(fn, O_RDONLY|O_NONBLOCK)) == -1) {
        perror("open() error for read end");
        exit(-1);
    }   

    if ((wfd = open(fn, O_WRONLY)) == -1) {
        perror("open() error for write end");
        exit(-1);
    }   

    if (write(wfd, out, strlen(out)+1) == -1) {
        perror("write() error");
        exit(-1);
    }   

    if (read(rfd, in, sizeof(in)) == -1) {
        perror("read() error");
        exit(-1);
    }   

    printf("read '%s' from the FIFO\n", in);
    close(wfd);
    close(rfd);

    // unlink a fifo
    unlink(fn);

    return 0;
}

参考

http://linux.die.net/man/3/mkfifo

http://www.cppblog.com/jackdongy/archive/2013/01/07/197055.html

相关推荐