Linux进程间的通信

一、无名管道Pipe

示意图:


1)管道就相当于队列的数据结构;

2)管道只适合半双工的通信方式;

3)只能用于具有亲缘关系的进程间通信;

4)管道操作不能同时读和写;读的时候要关闭写端;写的时候要关闭读端;

函数:

#include <unistd.h>
int pipe(int pipefd[2]);

说明:

参数:文件描述符:pipefd[0]   是读;pipefd[1]   是写;

返回值:0     成功;其他       失败;



举例:

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

int main()
{
        int fd[2];
        int pid;
        char *w_count="hello world!";
        char r_count[255];
        if(pipe(fd)!=0)
        {
        printf("create pipe fail.\n");
        return -1;
        }
        if((pid=fork())<0)
        {
                printf("create process  fail.\n");
                return -1;
        }

        else if(pid>0)
        {
                close(fd[0]);
                write(fd[1],w_count,strlen(w_count));
                close(fd[1]);
                wait();
        }
        else
        {
                sleep(2);//等待父进程写操作;
                close(fd[1]);
                read(fd[0],r_count,255);
                close(fd[0]);
                printf("child read:%s\n",r_count);
        }
        return 0;
}

运行结果:

[root@localhost ~]# ./pipe
child read:hello world!


二、有名管道FIFO

在shell中,我们可以用mkfifo命令建立一个管道文件:“mkfifo   myfifo”;

Fifo突破了pipe只能在父子进程中通信的局限性;这两个不相关的进程通过管道文件建立通信;

函数:

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

功能:建立管道文件;然后就可以对文件进行读写操作了;

参数:pathname是路径名称,mode是建立方式;

返回值:0  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值