查看: 92|回覆: 0

有名管道练习

[複製鏈接]

3

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-11-23
發表於 2025-5-8 09:23:00 | 顯示全部樓層 |閲讀模式
/********************************************************************************
*
* 在主程序中创建一个子程序,并在父进程中获取系统时间,并写入管道,子程序从管道中读取数据
* 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
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部