2024-8-13进程线程课后练习

1.运行日志写入

#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#define FIFE_PATH "/home/ubuntu/my_fifo1"

int main(int argc, const char *argv[])
{
	//1.判断管道文件是否存在,不存在则创建管道文件;
	if(access(FIFE_PATH,R_OK)!=0){
		int ret = mkfifo(FIFE_PATH,0777);
		if(ret==-1)
		{
			perror("创建管道文件失败");
			return -1;
		}
	}
	//2.打开管道文件:
	int fd=open(FIFE_PATH,O_RDWR);
	if(-1==fd){
		perror("打开文件失败");
		return -1;
	}
	//3.向管道文件里写入;
	char buf[200];
	while(1)
	{
		sleep(1);
		memset(buf,0,sizeof(buf));
		time_t rawtime;
		time(&rawtime);
		char *time_str=ctime(&rawtime);
		snprintf(buf,200,"%d/%s",getpid(),time_str);
		if(write(fd,buf,strlen(buf))==-1)
		{
			perror("写入文件失败");
			return -1;
		}
	}
	close(fd);
	return 0;
}

2.运行日志读取

#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#define FIFE_PATH "/home/ubuntu/my_fifo1"

int main(int argc, const char *argv[])
{
	//1.判断管道文件是否存在,不存在则创建管道文件;
	if(access(FIFE_PATH,R_OK)!=0){
		int ret = mkfifo(FIFE_PATH,0777);
		if(ret==-1)
		{
			perror("创建管道文件失败");
			return -1;
		}
	}
	//2.打开管道文件:
	int fd=open(FIFE_PATH,O_RDWR);
	if(-1==fd){
		perror("打开文件失败");
		return -1;
	}
	int t_fd = open("./time.txt", O_RDWR | O_CREAT | O_APPEND, 0666);
	if(-1==t_fd){
		perror("打开文件失败");
		return -1;
	}
	//3.读取管道文件里的内容;
	char buf[200];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		if(read(fd,buf,sizeof(buf)-1)==-1){
			perror("读取文件失败");
			return -1;
		}		
		if(write(t_fd,buf,strlen(buf))==-1){
			perror("写入文件失败");
			return -1;
		}
	}
	close(fd);
    close(t_fd);
	return 0;
}

3.time.txt文件

4.四张图代码的运行结果

1.

Parent has x = 0
Bye from process [父进程的PID] with x = 0
 

Child has x = 2
Bye from process [子进程的PID] with x = 2

2.

  • "L0\n" 将输出 1 次。
  • "L1\n" 将输出 2 次。
  • "Bye\n" 将输出 4 次。

3.

  • "L0\n" 将输出 1 次。
  • "L1\n" 将输出 2 次。
  • "L2\n" 将输出 4 次。
  • "Bye\n" 将输出 8 次。

4.

  • "L0\n" 将输出 1 次。
  • "L1\n" 仅在第一次 fork() 的父进程中输出 1 次。
  • "L2\n" 仅在第二次 fork() 的父进程中输出 1 次。
  • "Bye\n" 会被所有三个进程输出,因此输出 3 次。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值