1、日志模型
练习使用有名管道,多个进程写入文件,一个进程读取文件并写入日志文件
(1)父进程,创建多个子进程
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/errno.h>
#include<fcntl.h>
#include<time.h>
#define N 5
int main()
{
//创建子进程
//子进程调用process.c文件
for(int i=0; i<N; i++)
{
pid_t pid = fork();
if(pid == 0)
{
execl("./son","son",NULL);
}
}
//父进程等待
int status;
wait(&status);
return 0;
}
(2)子进程程序
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/errno.h>
#include<fcntl.h>
#include<time.h>
#include<string.h>
#include<sys/stat.h>
#define FIFO_PATH "./fifo"
int main()
{
//创建有名管道文件
if(access(FIFO_PATH, F_OK) != 0)
{
int ret = mkfifo(FIFO_PATH, 0777);
if(-1 == ret)
{
perror("create fifo failed:");
return -1;
}
}
//打开管道文件
int fd = open(FIFO_PATH, O_WRONLY);
//写入管道文件
char* buf = malloc(101);
int pid = getpid();
time_t t;
while(1)
{
time(&t);
memset(buf, 0, 101);
snprintf(buf, 100, "%s:%d\n",ctime(&t), pid);
write(fd, buf, strlen(buf));
}
free(buf);
buf = NULL;
return 0;
}
(3)读取管道文件,并写入日志文件
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/errno.h>
#include<fcntl.h>
#include<time.h>
#include<string.h>
#include<sys/stat.h>
#define FIFO_PATH "./fifo"
int main()
{
//创建有名管道文件
if(access(FIFO_PATH, F_OK) != 0)
{
int ret = mkfifo(FIFO_PATH, 0777);
if(-1 == ret)
{
perror("create fifo failed:");
return -1;
}
}
//打开管道文件
int fd = open(FIFO_PATH, O_RDONLY);
//以追加方式打开日志文件
int log_fd = open("./log.txt",O_WRONLY | O_TRUNC);
if(log_fd == -1)
perror("打开文件失败");
system("chmod 0777 log.txt");
//读取管道文件,并写入日志文件
char* buf = malloc(101);
while(1)
{
memset(buf, 0, 101);
read(fd, buf, 100);
write(log_fd, buf, strlen(buf));
}
free(buf);
buf = NULL;
return 0;
}