进程间通信之管道

进程间常见的通信方式之管道

1. 匿名管道pipe: 管道是一种半双工的通信方式,数据只能单向流动。一般会创建两个管道使其变为全双工,这个只能在具有亲缘关系的进程间使用,通常的父子进程之间。

举例:

int
main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <string>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (cpid == 0) {    /* Child reads from pipe */
        close(pipefd[1]);          /* Close unused write end */

        while (read(pipefd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);

        write(STDOUT_FILENO, "\n", 1);
"pipe.c" 48L, 1142C                                                                     31,43         33%

2. 有名管道FIFO:有名管道也是半双工的通信方式,但是它允许无亲缘关系的进程间通信。其实不管匿名管道与有名管道都是通过内核缓冲区实现的数据的传输,有名管道会在内核特殊的文件系统中建立一个文件,任何进程都可以打开它,当前进程结束时,这个文件还是存在的。当然重启之后就没有了,因为是在内存中

举例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>


int main()
{
        int rfd,wfd;
        fd_set rd_set;
        struct timeval timeout;
        char str[64] = "";
        mkfifo("fifo1", 0777);
        // open pipe file mode: 1. O_RDWR Mode; 2. make O_NONOBLOCK mode to  O_RDONLY & O_WRONLY open file.
        rfd = open("fifo1",O_RDONLY |O_NONBLOCK); // read pipe point
        if(rfd < 0)
        {
                perror("open fifo1 pipe file is failed!\n");
                return -1;
        }
        wfd = open("fifo1", O_WRONLY | O_NONBLOCK); //write pipe point
        if(wfd < 0)
        {
                perror("open fifo2 pipe file is failed!\n");
                return -1;
        }
"mkfifo.c" 67L, 1247C                                                                   16,23-30     顶端

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值