linux进程间通信:FIFO应用 /var/log/ 系统日志的模拟实现
生活随笔
收集整理的這篇文章主要介紹了
linux进程间通信:FIFO应用 /var/log/ 系统日志的模拟实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在類unix操作系統下存在這樣一個目錄/var/log/,主要是記錄操作系統相關的系統各個進程服務的日志信息
該日志系統的特性如下:
- 支持多進程并發寫入同一文件
- 不同進程日志信息可以寫入不同文件
- 支持使用head/tail/grep/cat/vi 等命令進行日志操作
我們可以利用mkfifo的原子特性來實現一個類似的日志系統,基本結構如下
寫入fifo的進程代碼如下:
/*************************************************************************> File Name: write_fifo.c> Author: > Mail: > Created Time: 二 9/24 12:16:37 2019************************************************************************/#include<stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>#define FIFO_NAME "testfifo"int main(int argc, char* argv[])
{int fd;char buf[100];//創建fifo mkfifo(FIFO_NAME, 0644);fd = open(FIFO_NAME, O_WRONLY);//每隔5秒向fifo中寫入數據while (1){memset(buf,0,100);sprintf(buf,"process %d : log \n",getpid());write(fd, buf,strlen(buf));sleep(5);}return 0;
}
守護進程代碼如下:
/*************************************************************************> File Name: daemon_fifo.c> Author: > Mail: > Created Time: 二 9/24 12:10:37 2019************************************************************************/#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LOG_PATH "/var/log/process.log"
#define FIFO_NAME "testfifo" int main()
{// 和寫入進程一樣 創建一個同名的fifo用作守護,int f= mkfifo(FIFO_NAME,0644);printf("mkfifo result %d \n");char public_buf[100];int fd;//以只讀的方式打開fifofd = open(FIFO_NAME,O_RDONLY);if (fd == -1)_exit(-1);memset(public_buf,0,100);int file_fd;//創建日志文件,可以追加寫,并提供全用戶及用戶組的讀寫權限file_fd = open(LOG_PATH,O_CREAT | O_RDWR | O_APPEND);if ( -1 == file_fd)_exit(-1);int read_len = 0;while(1){//循環從fifo中讀取數據read_len = read(fd,public_buf,100);if (read_len == -1)_exit(-1);//讀取出來之后執行下刷到日志操作else if (read_len > 0){printf("%s\n",public_buf);write(file_fd,public_buf,strlen(public_buf));}else{sleep(3);printf("write log failed \n");continue;}sleep(1);}close(file_fd);return 0;
}
總結
以上是生活随笔為你收集整理的linux进程间通信:FIFO应用 /var/log/ 系统日志的模拟实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 少了我的陪伴是哪首歌啊?
- 下一篇: linux进程间通信:FIFO实现进程间