/*************** 进程A *************/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
int main(){
// 1.创建命名管道文件
int ret = mkfifo( "./fifo_test", 0644);
if( ret == -1 ){ //创建失败处理
fprintf( stderr, "mkfifo error,errno:%d,%s\n", errno, strerror(errno));
return 1;
}
// 2.打开命名管道文件
int fifo_pd = open( "./fifo_test", O_WRONLY);
if( fifo_pd == -1 ){ //打开失败处理
fprintf( stderr, "open error,errno:%d,%s", errno, strerror(errno));
return 2;
}
// 3.获取并整理时间信息
char buf[128] = {0};
time_t now = time(NULL);
struct tm *local = localtime(&now);
sprintf( buf, "%04d年%02d月%02d日 %02d:%02d:%02d\n",
local->tm_year+1900, local->tm_mon + 1, local->tm_mday,
local->tm_hour, local->tm_min, local->tm_sec);
// 4.往管道文件里面写入时间信息
write( fifo_pd, buf, sizeof(buf));
close(fifo_pd); //关闭管道文件
return 0;
}
/******************* 进程B********************/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
int main(){
// 1.打开管道文件
int fifo_pd = open( "./fifo_test", O_RDONLY);
if( fifo_pd == -1 ){ //打开失败错误处理
fprintf( stderr, "open error,errno:%d,%s", errno, strerror(errno));
return 1;
}
// 2.打开记录日志的文件
int log = open( "log.txt", O_WRONLY|O_CREAT|O_APPEND, 0664);
if( log == -1 ){
fprintf( stderr, "open error,errno:%d,%s", errno, strerror(errno));
return 2;
}
char buf[128] = {0};
// 3.从管道文件中读取信息
read( fifo_pd, buf, 50);
// 4.往日志文件里面写入信息
write( log, buf, strlen(buf));
close(fifo_pd);
close(log);
return 0;
}