Linux下进程间通信-------管道通信

先来看原理:

 特点 :

1.半双工的通信方式(通信期间双方都可以发送/接收文件,但是不能双方同时发送/接收数据)

2.pipe只能用于父子进程间的通信

3.mkfifo可用于任意进程间的通信

代码逐步实现

首先创建管道文件:

 然后ls查看是否创建(因为我提前都写过了,所有文件夹中写端和读端都有了)

 然后进行写端的编写:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <signal.h>
 
void sig_fun(int sig)//当读端或写端其中一方出错时不会直接终止掉程序 而是返回一个信号值
{
    printf("sig = %d \n",sig);
}
 
int main()
{
    signal(SIGPIPE,sig_fun);
    int fdw = open("fifo",O_WRONLY);//打开管道文件 只写权限(该代码是以任意两进程间通信为例)
    assert(fdw != -1);

    while(1)//循环写入程序
    {
        printf("fdw = %d\n",fdw);

        char buff[128] = {0};//将写入的数据存到buff中
        printf("inputs:\n");
        fgets(buff,128,stdin);
        if(strncmp(buff,"end",3) == 0)//如果输入"end"则终止掉程序
        {
            break;
        }
        write(fdw,buff,strlen(buff));//将数据写入管道文件中
    }
    close(fdw); //关闭文件描述符
    exit(0);

}

读端的编写:

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

int main()
{
    int fdr = open("fifo",O_RDONLY);//从管道文件中读取数据  只读
    assert(fdr != -1);

    printf("fdr = %d \n",fdr);

    while(1)
    {
        char buff[128] = {0};
        int n = read(fdr,buff,127);
        if(n == 0) //当写端GG的时候  读端没有读取到数据  然后读端跟着一起GG
        {
            break;
        }
        printf("  \n   buff = %s \n,n = %d \n",buff,n);
    }
    close(fdr);//
    exit(0);

}

然后上述代码是任意两进程间的通信

使用的创建命令是mkfifo

然后下面来看pipe(父子进程间的通信)

先通过详细命令man pipe可以看到:

 pipe需要传入两个文件描述符:fd[0]是读的文件描述符

                                                   fd[1]是写的文件描述符

下面来看代码实现:

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

int main()
{
    int fd[2];\\fd[0] 读   fd[1]  写
    int res = pipe(fd);
    assert(res != -1);
    
    pid_t pid = fork();
    assert(pid != -1);
    
    if(pid == 0) //pid == 0 是在子进程那块
    {
        close(fd[1]);
        char buff[128] = {0};
        read(fd[0],buff,127);
        printf("child read:%s\n",buff);
        close(fd[0]);
    }    
    else //否则就在父进程那块
    {
        close(fd[0]);
        char buff[128] = {0};
        fgets(buff,128,stdin);        

        write(fd[1],buff,strlen(buff));
        close(fd[1]);
    }
}

该代码在执行之后,父子进程都在阻塞,父进程在等待输入fgets那块阻塞,子进程在read那块阻塞,然后你在输入之后,回车,子进程就会读出数据!

“如果你的长大还让父母那么劳累,那么你长大的意义是什么!”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值