进程间通信和同步—管道

半双工管道

管道:将某个进程的输出和另一个进程的输入相连接的单向通信的方法。故称为“半双工” 在shell 中管道用“|”表示

pipe()函数
#include <unistd.h>
int pipe(int filedes[2]);
//  filedes 文件描述符数组,用于保存管道返回的两个文件描述符。(第一个读,第二个写)
//  成功返回0 否则 -1.
例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
        int result = -1;
        int fd[2],nbytes;   // 声明两个文件描述符 ,一个读 一个写。
        pid_t pid;
        char string[] = "hello pipe";
        char readbuffer[80];
        int* write_fd = &fd[1];   // 第二个为写。
        int* read_fd = &fd[0];

        result = pipe(fd);  // 创建管道
        if(-1 == result)
        {
                printf("error \n");
                return -1;
        }
        pid = fork();  // 复制进程。
        if(-1 == pid)
        {
                printf("fork error");
                return -1;
        }
        if(0 == pid)  
        {
                close(*read_fd);
                result = write(*write_fd,string,strlen(string));  // 子进程写。
                return 0;
        }else {
                close(*write_fd);
                nbytes = read(*read_fd,readbuffer,sizeof(readbuffer));  // 父进程读
                printf("receive %d data, is :%s",nbytes,readbuffer);
        }
        return 0;
}                                                                                             

管道进行写入操作时,当写入数据小于128K 时,写入是非原子的。
管道最大写入阈值 PIPE_BUF (至少是512),数值受内核版本限制。

命名管道

与普通管道方式相似。不同:

  1. 在文件系统中命名管道是以设备特殊文件的形式存在的
  2. 不同的进程可以通过命名管道共享数据。
创建FIFO

命令: mkfifo
函数 mkfifo()

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

在FIFO 中必须用一个open()函数来显示的建立连接到管道的通道,一般来说FIFO总是处于阻塞状态的。可在open() 调用中使用O_NONBLOCK标记,关闭默认阻塞动作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值