管道文件的文件特性

目录

问题

在 /tmp 目录下创建一条命名管道,命名管道的名称用户决定,然后设计两个程序要求进程 A获取当前系统时间(time-->ctime)并写入到命名管道,进程B从命名管道中读取数据并存储在一个名字叫做 log.txt 的文本中。

进程A

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

int main() 
{
    char *fifo_path = "/tmp/myfifo"; // 命名管道路径
    int fd;
    time_t current_time;
    char *time_str;

    // 创建命名管道
    mkfifo(fifo_path, 0664);

    // 打开命名管道
    fd = open(fifo_path, O_WRONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 获取当前系统时间并转换为字符串
    current_time = time(NULL);
    time_str = ctime(&current_time);

    // 写入当前时间到命名管道
    write(fd, time_str, strlen(time_str) + 1);

    // 关闭命名管道
    close(fd);

    return 0;
}

进程B

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

#define max_buf 128

int main() 
{
    char *fifo_path = "/tmp/myfifo"; // 命名管道路径
    int fd;
    char buf [max_buf];

    // 打开命名管道
    fd = open(fifo_path, O_RDONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 从命名管道中读取数据
    read(fd, buf, max_buf);

    // 关闭命名管道
    close(fd);

    // 写入数据到 log.txt 文本文件
    FILE *fp = fopen("log.txt", "w+");
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    fprintf(fp, "%s", buf);
    fclose(fp);

    return 0;
}

结果

image

问题

如果进程A向命名管道中写入了数据之后就关闭了命名管道,而进程B从命名管道中读取了进程A写入的部分数据之后就关闭了命名管道,请问下次打开命名管道之后是否可以继续读取上一次遗留的数据?

答:不会,由上结果可知管道由内核申请的缓存区,在管道关闭后自动被清空,无法再读取上一次遗留数据。即使进程 A 向命名管道中写入了数据后关闭了管道,进程 B 也只能读取到进程 A 写入管道的部分数据,因为管道是一个先进先出的数据结构,进程 B 在关闭管道后,任何剩余的数据都会被丢弃。每次打开管道都是一个全新的读取过程,无法获取之前写入的数据。

posted @   待会儿去码头整点薯条  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示