管道的学习
在 /tmp 目录下创建一条命名管道,命名管道的名称用户决定,然后设计两个程序,要求进程A获取当前系统时间(time-->ctime)并写入到命名管道,进程B从命名管道中读取数据并存储在一个名字叫做log.txt的文本中。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
// 创建一个管道文件
// int ret = mkfifo("./fifo1", 0644);
// if (-1 == ret)
// {
// printf("mkfifo fail\n");
// return -1;
// }
// 打开管道文件
int pipe_fd = open("./fifo1", O_RDWR);
if (-1 == pipe_fd)
{
printf("open pipe fail");
return -1;
}
// 以只写的方式打开或创建文件"log.txt"
FILE *file = fopen("./log.txt", "wb+");
if (NULL == file)
{
perror("fopen file failed!\n");
exit(1);
}
time_t timep;
struct tm *timerow;
// 创建一个读取缓存区
char read_buf[128] = {0};
char write_buf[128] = {0};
// 创建一个进程
int child_pid = fork();
if (child_pid > 0) // 父进程
{
//向管道中读取相关信息
int ret = read(pipe_fd, read_buf, sizeof(read_buf));
wait(NULL); //等待子进程结束
printf("my is father,this is what I write:%s\n",read_buf);
if (ret != sizeof(read_buf))
{
printf("read fail\n");
}
//将读到的数据写入log.txt文本中
fwrite(read_buf, 1, sizeof(write_buf), file);
//关闭管道以及log.txt文本
close(pipe_fd);
fclose(file);
}
else if (child_pid == 0) // 子进程
{
// 获取当前时间戳
timep = time(NULL);
// 将时间戳的地址作为参数传递给函数localtime
timerow = localtime(&timep);
// 将数据输出到缓存区中
sprintf(write_buf, "%d年%d月%d日,星期%d,%d:%d:%d",
timerow->tm_year + 1900,
timerow->tm_mon + 1,
timerow->tm_mday,
timerow->tm_wday,
timerow->tm_hour,
timerow->tm_min,
timerow->tm_sec);
//向管道写入缓存区里的时间
write(pipe_fd, write_buf, sizeof(write_buf));
printf("my is child,this is what I write:%s\n",write_buf);
}
else //进程创建失败的情况
{
printf("fork fail\n");
return -1;
}
//关闭管道以及log.txt文本
//close(pipe_fd);
//fclose(file);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)