进程间通信之管道

管道(pipe)是进程间通信的一种方式。

API:

int pipe(int pipefd[2]);

DEMO:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define MAXLINE 4096

int main(int argc, char **argv) {
    int n;
    int fd[2];
    pid_t pid;
    char line[MAXLINE];
    
    if (pipe(fd) < 0) {
        perror("pipe error");
        exit(1);
    }
    if ( (pid = fork()) < 0) {
        perror("fork error");
        exit(1);
    } else if (pid > 0) {
        close(fd[0]);
        write(fd[1], "hello world\n", 12);
    } else {
        close(fd[1]);
        n = read(fd[0], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
    }
    exit(0);
}

管道的特点:

1. 管道是半双工的(数据只能在一个方向上流动)

2. 管道只能在具有公共祖先的两个进程之间使用

对于从父进程到子进程的管道,父进程关闭管道的读端fd[0],子进程关闭写端fd[1]。

对于从子进程到父进程的管道,父进程关闭fd[1],子进程关闭fd[0]。

posted @ 2017-03-14 09:58  Sawyer Ford  阅读(234)  评论(0编辑  收藏  举报