Linux下进程通信之:有名管道

进程通信:进程与进程间的数据交换,称为进程通信。进程通讯的方式有:共享内存、信号量、管道、消息队列、socket等等。

管道:是一种基于文件的描述符,可以调用read、write和close等操作文件的接口来操作。它是基于文件描述符的通信方式,它是半双工模式。分为有名管道和无名管道。

无名管道:只适用于父子进程之间通信;管道能够把信息从一个进程的地址空间拷贝到另一个进程的地址空间。fd[0]为管道里的读取端,fd[1]则为管道的写入端。管道是一个单向通信信道,如果进程间要进行双向通信,通常需要定义两个管道。

有名管道:有自己的名字和访问权限的限制,就像一个文件一样。它可以用于不相关进程间的通信,进程通过使用管道的名字获得管道。通过系统调用read(), write()函数进行读写操作来实现。

-------------------------write--------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int fd;
    char buff[] = "hello,is me!\n";
    remove("temp_fifo");
    if((mkfifo("temp_fifo", O_CREAT|O_RDWR|0777))<0)
    {
        printf("mkfifo is error/n");
        return -1;
    }
    if((fd = open("temp_fifo",O_WRONLY))<0)
    {
        printf("open is error/n");
        return -1;
    }
    if(write(fd,buff,strlen(buff))<0)
    {
        printf("write is error/n");
        return -1;
    }

    close(fd);
    return 0;
}


-------------------------read--------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int fd;
    char buff[32] = {0};
 
    if((fd = open("temp_fifo",O_RDONLY))<0)
    {
        printf("open is  error/n");
        return -1;
    }
    if((read(fd,buff,sizeof(buff)))<0)
    {
        printf("write is  error/n");
        return 0;
    }

    printf("buff: %s/n", buff);
    close(fd);
    return 0;
}

fifo_test1.c负责写,fifo_test2.c负责读。结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值