进程与有名管道练习,日志模型

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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值