linuxC多进程通讯---使用fifo实现一个log日志系统

文章目录

任务

Log日志系统
•各个进程往FIFO管道写入数据
•守护进程使用FIFO接收各个进程的输出日志信息
•并将FIFO中的数据写到对应的日志文件中
在这里插入图片描述

举例

#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;
}

#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;
}

发布了349 篇原创文章 · 获赞 6 · 访问量 9751

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/99815466