注:前言、目录见 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);
}
}
示例截图