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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值