2024.8.28作业

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

#define FIFO1 "/tmp/pipe1"
#define FIFO2 "/tmp/pipe2"

int main() {
    int fd1, fd2;
    char buffer[1024];
    pid_t pid;

    // 创建两个有名管道
    if (mkfifo(FIFO1, 0666) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    if (mkfifo(FIFO2, 0666) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        // 子进程
        fd1 = open(FIFO1, O_RDONLY);
        fd2 = open(FIFO2, O_RDONLY);

        // 读取管道1的数据
        read(fd1, buffer, sizeof(buffer) - 1);
        buffer[strcspn(buffer, "\n")] = 0; // 去除换行符
        printf("Child read from pipe1: %s\n", buffer);

        // 读取管道2的数据
        read(fd2, buffer, sizeof(buffer) - 1);
        buffer[strcspn(buffer, "\n")] = 0; // 去除换行符
        printf("Child read from pipe2: %s\n", buffer);

        // 关闭文件描述符
        close(fd1);
        close(fd2);
    } else {
        // 父进程
        fd1 = open(FIFO1, O_WRONLY);
        fd2 = open(FIFO2, O_WRONLY);

        // 写入管道1的数据
        write(fd1, "Hello from pipe1\n", 16);

        // 写入管道2的数据
        write(fd2, "Hello from pipe2\n", 16);

        // 关闭文件描述符
        close(fd1);
        close(fd2);

        // 等待子进程完成
        wait(NULL);
    }

    // 父进程删除有名管道
    unlink(FIFO1);
    unlink(FIFO2);

    return 0;
}
ubuntu@ubuntu:day5$ gcc 1.c
1.c: In function ‘main’:
1.c:15:9: warning: implicit declaration of function ‘mkfifo’ [-Wimplicit-function-declaration]
     if (mkfifo(FIFO1, 0666) == -1) {
         ^~~~~~
1.c:55:9: warning: implicit declaration of function ‘wait’; did you mean ‘main’? [-Wimplicit-function-declaration]
         wait(NULL);
         ^~~~
         main
ubuntu@ubuntu:day5$ ./a.out 
Child read from pipe1: Hello from pipe1�TP�Q
Child read from pipe2: Hello from pipe2�TP�Q
ubuntu@ubuntu:day5$ 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值