【实验三】

本文通过示例代码展示了如何使用有名管道(FIFO)进行进程间的通信。程序创建了一个读进程和两个写进程,其中一个写进程不断写入数据,读进程则读取并显示数据,实现了简单的数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

就是不写 readme !

涉及知识点:

  • 有名管道
  • 进程通信
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main() {
    int fd, fd1, fd2;
    char buf[1024];

    if (mkfifo("./hello.txt", 0777) < 0) {
        perror("failed to open the FIFO mkfifo");
        return 1;
    }

    if ((fd1 = open("./hello.txt", O_CREAT|O_RDWR)) == -1) {
        perror("failed to open the FIFO hello.txt");
        return 1;
    }
    
    if ((fd = open("./19407010204.txt", O_RDWR)) == -1) {
        perror("failed to open the FIFO 1911");
        return 1;
    }
    
    while (1) {
        read(fd, buf, sizeof(buf)); // buf
        printf("read content is : %s\n", buf);
        
        write(fd1, buf, sizeof(buf));
        printf("write pipe: %s\n", buf);
        sleep(10);
    }

    close(fd);
    close(fd1);

    return 0;
}


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

int main() {
    int fd, fd1, fd2;
    char buf[1024], buf2[1024];
    
    fd = open("./hello.txt", O_RDONLY);
    if (fd < 0) {
        printf("err!!");
        return -1;
    }
    

    while (1) {
        read(fd, buf, sizeof(buf)); // buf
        printf("read content is : %s\n", buf);
        sleep(10);
    }
    close(fd);
    return 0;
}


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

int main() {
    int fd;
    char s[] = "This is a test programmer of process & IPC";

    if ((fd = open("./19407010204.txt", O_CREAT|O_RDWR,0666)) == -1) {
        perror("failed to open the FIFO");
        return 1;
    }
    
    while (1) {
        write(fd, s, sizeof(s));
        printf("Write: %s\n", s);
        sleep(3);
    }

    close(fd);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值