5.7 FIFO应用:LOG日志系统的实现

1、实验代码
process.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define FIFO_SERVER "fifo_log_server"

int main (void)
{
	mkfifo (FIFO_SERVER, 0644);
	int fifo_fd;
	fifo_fd = open (FIFO_SERVER, O_WRONLY);
	char buf[100];
	while (1)
	{
		memset (buf, 0, 100);
		sprintf (buf, "process %d: log----\n", getpid());
		write (fifo_fd, buf, strlen (buf));
		sleep (5);
	}
	return 0;
}

mylog_daemon.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define handle_error(msg) \
    {perror(msg);exit(EXIT_FAILURE);}
#define FIFO_SERVER "fifo_log_server"
#define LOG_PATHNAME    "/var/log/process.log"

int main (void)
{
	mkfifo (FIFO_SERVER, 0644);
	int ret_from_fork;
	char public_buf[100];
		
	int fifo_fd;
	fifo_fd = open (FIFO_SERVER, O_RDONLY);
	memset (public_buf, 0, 100);

	int fd;
	fd = open (LOG_PATHNAME, O_WRONLY | O_CREAT | O_APPEND);
    if (fd == -1)
        handle_error("open");
	int read_len;
	while (1)
	{
		read_len = read (fifo_fd, public_buf, 100);
		if (read_len == -1)
            handle_error("read")
		else if (read_len > 0)
		{
			printf ("%s\n", public_buf);
			write (fd, public_buf, strlen (public_buf));
		}
		else
		{
			sleep (3);
			continue;
		}
		sleep (1);
	}
	close (fd);
	return 0;
}

2、实验结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值