有名管道练习

/********************************************************************************
*
* 在主程序中创建一个子程序,并在父进程中获取系统时间,并写入管道,子程序从管道中读取数据
* author:jindouliu2024@163.com 
* date:2025.5.8
* Copyright (c)  2024-2025   jindouliu2024@163.com   All right Reserved
* 
********************************************************************************/
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

int main() {
    time_t now;
    struct tm *time_info;
    char buffer[80];
    char buffer1[80];
    int fifo_fd;

    // 创建有名管道
    int ret = mkfifo("./fifo2", 0664);
    if (ret == -1) {
        perror("mkfifo failed");
        return -1;
    }

    // 创建一个子进程
    pid_t child_pid = fork();
    if (child_pid > 0) {
        // 父进程:以写模式打开管道
        fifo_fd = open("./fifo2", O_WRONLY);
        if (fifo_fd == -1) {
            perror("open fifo failed");
            return -1;
        }

        // 获取当前时间
        now = time(NULL);

        // 将时间转换为本地时间
        time_info = localtime(&now);

        // 格式化时间
        strftime(buffer, sizeof(buffer), "当前时间:%Y年%m月%d日 %H:%M:%S", time_info);

        // 向管道写入数据
        ret = write(fifo_fd, buffer, strlen(buffer) + 1); // 写入字符串长度 + 1(包括'\0')
        if (ret == -1) {
            perror("write failed");
            close(fifo_fd);
            return -1;
        }

        // 关闭管道
        close(fifo_fd);

        // 等待子进程完成
        wait(NULL);
    } else if (child_pid == 0) {
        // 子进程:以读模式打开管道
        fifo_fd = open("./fifo2", O_RDONLY);
        if (fifo_fd == -1) {
            perror("open fifo failed");
            return -1;
        }

        // 从管道读取数据
        ret = read(fifo_fd, buffer1, sizeof(buffer1) - 1);
        if (ret == -1) {
            perror("read failed");
            close(fifo_fd);
            return -1;
        }

        // 确保字符串以空字符结尾
        buffer1[ret] = '\0';

        // 输出读取的数据
        printf("%s\n", buffer1);

        // 关闭管道
        close(fifo_fd);
    } else {
        perror("fork failed");
        return -1;
    }

    return 0;
}
````

来源链接:https://www.cnblogs.com/lradian/p/18865624

© 版权声明
THE END
支持一下吧
点赞10 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容