/**********************************************************************************
*
-
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;
}