进程A获取当前系统时间并写入到命名管道,进程B从命名管道中读取数据并存储在一个名字叫做log.txt的文本中。
/**********************************************************************************
*
-
file name: pipe1.c
-
author : A13326981379@163.com
-
date : 2024/05/31
-
function : 获取系统时间,将系统时间写入管道
-
note : None
-
CopyRight (c) 2024-2024 A13326981379@163.com All Right Reseverd
- *******************************************************************************/
进程A代码:
#include <errno.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
char *wday[] = {"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
time_t timep;
struct tm *p;
time(&timep);
p = localtime(&timep);
printf("%d年%02d月%02d日 ", (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday);
printf("%s %02d:%02d:%02d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
char msg[400] = {0}; // 修改为 400 字符
sprintf(msg, "%d年%02d月%02d日 %s %02d:%02d:%02d\n", (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday, wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
int fifd = open("./fifo1",O_RDWR);
if (fifd == -1)
{
fprintf(stderr,"fifo pipe error,error:%d,%s",errno,strerror(errno));
exit(1);
}
write(fifd,msg,strlen(msg));
close(fifd);
return 0;
}
/**********************************************************************************
*
-
file name: pipe2.c
-
author : A13326981379@163.com
-
date : 2024/05/31
-
function : 将管道中的信息读出来写入文本
-
note : None
-
CopyRight (c) 2024-2024 A13326981379@163.com All Right Reseverd
- *******************************************************************************/
进程B的代码:
#include <errno.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
FILE *file_fd = fopen("log.txt","a");
if (file_fd == NULL)
{
fprintf(stderr,"fifo pipe error,error:%d,%s\n",errno,strerror(errno));
exit(1);
}
int fifd = open("./fifo1",O_RDWR);
if (fifd == -1)
{
fprintf(stderr,"fifo pipe error,error:%d,%s",errno,strerror(errno));
exit(1);
}
char buf[128] = {0};
read(fifd,buf,128);
fprintf(file_fd,"%s",buf);
fclose(file_fd);
close(fifd);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)