喙审 发表于 2025-5-29 10:55:59

有名管道练习

/********************************************************************************
*
* 在主程序中创建一个子程序,并在父进程中获取系统时间,并写入管道,子程序从管道中读取数据
* 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;
    char buffer1;
    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 = '\0';

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

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

    return 0;
}
````
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

洪思思 发表于 2025-10-10 05:30:31

这个好,看起来很实用

仰翡邸 发表于 2025-11-19 18:37:49

鼓励转贴优秀软件安全工具和文档!

博咱 发表于 2025-12-11 01:32:15

热心回复!

盗衍 发表于 2025-12-13 16:21:01

yyds。多谢分享

骛扼铮 发表于 2025-12-26 06:50:44

谢谢分享,辛苦了

段干叶农 发表于 2026-1-14 14:46:56

谢谢分享,试用一下

褥师此 发表于 2026-1-17 00:05:41

这个有用。

鞍注塔 发表于 2026-1-17 12:24:14

新版吗?好像是停更了吧。

遇玷 发表于 2026-1-19 02:30:46

收藏一下   不知道什么时候能用到

于映雪 发表于 2026-1-20 02:30:07

感谢分享,学习下。

趣侮 发表于 2026-1-24 13:04:42

热心回复!

愤血冒 发表于 2026-1-25 10:53:00

喜欢鼓捣这些软件,现在用得少,谢谢分享!

垢峒 发表于 2026-1-28 03:12:54

这个好,看起来很实用

梅克 发表于 2026-1-29 03:22:14

喜欢鼓捣这些软件,现在用得少,谢谢分享!

酝垓 发表于 2026-1-29 06:18:31

很好很强大我过来先占个楼 待编辑

即息极 发表于 2026-1-30 08:28:02

分享、互助 让互联网精神温暖你我

闻人莹华 发表于 2026-2-6 12:42:33

东西不错很实用谢谢分享

盛天欣 发表于 2026-2-7 04:45:16

这个好,看起来很实用

汝雨竹 发表于 2026-2-8 04:05:41

收藏一下   不知道什么时候能用到
页: [1] 2
查看完整版本: 有名管道练习