多进程多路输入输出--有名管道FIFO

多进程输入,非阻塞输出

  • 各个进程使用父子进程,分别完成读写

缺点

应用程序中同时处理多路输入输出流,若设置多进程,分别处理一条数据通路,将新产生进程间的同步与通信问题, 使程序变得更加复杂;

比较好的方法是使用I/O多路复用 如此操作

多进程处理多路输入输出

在这里插入图片描述

代码实现

a.c
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/*fork*/
#include <unistd.h>
int main()
{
    // 1.创建文件mkfifo fifo1 fifo2
    // 2.打开文件
    int fd1 = open("fifo1", O_WRONLY);//写
    int fd2 = open("fifo2", O_RDONLY);//读

    char write_buff[32] = {0};
    char read_buff[32] = {0};
    //创建子进程
    pid_t pid;
    pid = fork();

    if (pid == 0)
    {
        while (1)
        {
            scanf("%s", write_buff);
            write(fd1, write_buff, 32);
        }
    }
    else if (pid > 0)
    {
        while (1)
        {
            read(fd2, read_buff, 32);
            printf("A收到: %s\n", read_buff);
        }
    }
    close(fd1);
    close(fd2);
    return 0;
}
b.c
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/*fork*/
#include <unistd.h>
int main()
{
    // 1.创建文件mkfifo fifo1 fifo2
    // 2.打开文件
    int fd1 = open("fifo1", O_RDONLY);//读
    int fd2 = open("fifo2", O_WRONLY);//写

    char write_buff[32] = {0};
    char read_buff[32] = {0};
    //创建子进程
    pid_t pid;
    pid = fork();

    if (pid == 0)
    {
        while (1)
        {
            scanf("%s", write_buff);
            write(fd2, write_buff, 32);
        }
    }
    else if (pid > 0)
    {
        while (1)
        {
            read(fd1, read_buff, 32);
            printf("B收到: %s\n", read_buff);
        }
    }
    close(fd1);
    close(fd2);
    return 0;
}

执行结果

在这里插入图片描述

6.非原创

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值