Unix/Linux进程间通信——管道

管道的特性:
1. 半双工通信;
2. 只能在父进程和子进程或兄弟进程之间通信;

Unix/Linux中使用pipe函数创建管道,原型如下:
#include <unistd.h>

int pipe(int fildes[2]);
成功返回0,失败返回-1,参数fildes为返回的两个文件描述符,fildes[0]用于读,fildes[1]用于写。

实例如下:
/* http://beej.us/guide/bgipc/example/pipe1.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

int main(void)
{
	int pfds[2];
	char buf[30];

	if (pipe(pfds) == -1) {
		perror("pipe");
		exit(1);
	}

	printf("writing to file descriptor #%d\n", pfds[1]);
	write(pfds[1], "test", 5);
	printf("reading from file descriptor #%d\n", pfds[0]);
	read(pfds[0], buf, 5);
	printf("read \"%s\"\n", buf);

	return 0;
}

使用fork的实例:
/* http://beej.us/guide/bgipc/example/pipe2.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
        int pfds[2];
        char buf[30];

        pipe(pfds);

        if (!fork()) {
                printf(" CHILD: writing to the pipe\n");
                write(pfds[1], "test", 5);
                printf(" CHILD: exiting\n");
                exit(0);
        } else {
                printf("PARENT: reading from pipe\n");
                read(pfds[0], buf, 5);
                printf("PARENT: read \"%s\"\n", buf);
                wait(NULL);
        }

        return 0;
}

另一个例子:
/* http://beej.us/guide/bgipc/example/pipe3.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
        int pfds[2];

        pipe(pfds);

        if (!fork()) {
                close(1);       /* close normal stdout */
                dup(pfds[1]);   /* make stdout same as pfds[1] */
                close(pfds[0]); /* we don't need this */
                execlp("ls", "ls", NULL);
        } else {
                close(0);       /* close normal stdin */
                dup(pfds[0]);   /* make stdin same as pfds[0] */
                close(pfds[1]); /* we don't need this */
                execlp("wc", "wc", "-l", NULL);
        }

        return 0;
}
该程序相当于执行命令ls | wc -l。

你可能感兴趣的:(Unix/Linux进程间通信——管道)