进程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;
}

浙公网安备 33010602011771号