Linux--进程间通信(一)-管道(pipe)通信

76 篇文章 5 订阅

1、管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系
2、有名管道 (named pipe) : 有名管道也是半双工的通信方式,但是它允许无亲缘关系进程间的通信


 这个例子是,父进程创建子进程,父进程向子进程通过管道发送一个字符串,子进程读取该字符串显示并倒序后发送到父进程,父进程读取该倒序后的字符串并打印出来。

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


char sendbuf[] = "This is a pipe test!";
char recbuf[22];
char parrecbuf[22];

void reverse(char *str1){/*字符倒序函数*/

    if (str1 == NULL) return;
    char *p = str1;
    char *q = str1;
    while (*q)  ++q;
    q--;
    while(q > p){

        char t = *p;
        *p++ = *q;
        *q-- = t;
    }
}

int main() {

    int mypipe[2],fd;

    if ( pipe(mypipe) < 0) { perror("pipe faild"); exit(0); }
    if ( (fd=fork()) < 0) { perror("fork faild"); exit(0); }
    if (fd == 0) {
        read (mypipe[0],recbuf,strlen(sendbuf));
        printf("The child process get: %s\n",recbuf );
        reverse(recbuf);//倒序字符
        write(mypipe[1],recbuf,strlen(recbuf));//向管道内写入倒序后的字符串
    }
    if (fd > 0) {
        write(mypipe[1],sendbuf,strlen(sendbuf));
        sleep(10);//等待子进程从管道将数据取走
        read(mypipe[0],parrecbuf,strlen(sendbuf));
        printf("The parent process get: %s\n",parrecbuf );
        wait();//防止僵尸进程
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值