日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

linux进程间通信:FIFO应用 /var/log/ 系统日志的模拟实现

發布時間:2023/11/27 生活经验 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux进程间通信:FIFO应用 /var/log/ 系统日志的模拟实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在類unix操作系統下存在這樣一個目錄/var/log/,主要是記錄操作系統相關的系統各個進程服務的日志信息

該日志系統的特性如下:

  1. 支持多進程并發寫入同一文件
  2. 不同進程日志信息可以寫入不同文件
  3. 支持使用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/ 系统日志的模拟实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。