《Linux编程》上机作业 ·005【进程管理与通信】

注:前言、目录见 https://blog.csdn.net/qq_44220418/article/details/108428971

友情提醒:仅供参考理解,请勿直接复制粘贴

友情提醒:仅供参考理解,请勿直接复制粘贴

友情提醒:仅供参考理解,请勿直接复制粘贴

文章目录

第一题

了解有关进程,信号和进程通信与并发控制等基本概念,掌握进程创建和执行流程控制的基本方法,熟悉和掌握利用管道,消息队列和共享存储区实现进程间的通信的方法。


实验内容
\qquad 设计一个多进程并发运行的程序,它由不同的进程完成下列工作:
\qquad (1)数据输入进程
\qquad\qquad 负责按接收到的数据文件名将该文件中的字串数据交给数据处理进程进行处理。
\qquad (2)数据处理进程
\qquad\qquad 完成由键盘输入指定数据文件名传给数据输入进程,并将接收到的来自输入进程的字串数据打印在屏幕上,同时将其中的字符串写入文件string.txt中,数字串写入文件number.txt中。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#define N 10000
#define NUM 100

char str[N];		// 文件名字符串
char buf[N];		// 文化内容字符串
char strs[NUM][N];	// 文件内容按行分割字符串
char *part;			// 切割字符串

int cnt = 0;		// 文件内容有效行数

// 判断是否纯数字
int is_num(char* str)
{
	int len = strlen(str);
	for (int i = 0; i < len; ++i)
		if (str[i] < '0' || str[i] > '9')
			return 0;
	return 1;
}

int main(void)
{
	// 创建无名管道
	int fd[2];
	if (pipe(fd) < 0)
	{
		perror("pipe error");
		exit(1);
	}

	// 创建父子进程
	pid_t pid;
	if ((pid = fork()) < 0)
	{
		perror("fork error");
		exit(1);
	}
	else if (pid == 0)  // 子进程
	{
		// 子进程接受输入
		scanf("%s", str);

		// 将输入的字符串通过管道传给父进程
		close(fd[0]);
		write(fd[1], str, sizeof(str));
		close(fd[1]);
	}
	else  // 父进程
	{
		// 父进程等待子进程完毕
		wait(0);

		// 父进程通过管道读取输入
		close(fd[1]);
		read(fd[0], &str, sizeof(str));
		close(fd[0]);

		// 打开输入文件,创建预输出文件
		int fd1 = open(str, O_RDONLY);
		int fd_s = open("string.txt", O_CREAT | O_TRUNC | O_RDWR, 0777);
		int fd_n = open("number.txt", O_CREAT | O_TRUNC | O_RDWR, 0777);

		// 读取输入文件字符串
		read(fd1, buf, sizeof(buf) - 1);

		// 按行切割字符串
		char* buff = buf;
		while ((part = strsep(&buff, "\n")) != NULL)
			strcpy(strs[cnt++], part);

		// 打印每行的字符串,进行判别,分类输出
		for (int i = 0; i < cnt; ++i)
		{
			printf("%s\n", strs[i]);
			if (is_num(strs[i]))
			{
				strcat(strs[i], "\n");
				write(fd_n, strs[i], strlen(strs[i]));
			}
			else
			{
				strcat(strs[i], "\n");
				write(fd_s, strs[i], strlen(strs[i]));
			}
		}

		// 关闭文件
		close(fd1);
		close(fd_n);
		close(fd_s);
	}
}

示例截图
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

God-Excious

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值