/********************************************************************************
*
* 在主程序中创建一个子程序,并在父进程中获取系统时间,并写入管道,子程序从管道中读取数据
* 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
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容