操作系统实验上机

实验名称 实验序号 实验日期 实验人
多进程编程 2 公元2077 rytter

一、实验题目

image-20220428212057215

image-20220428212115524

二、相关原理和知识

  1. fork()函数实现多进程
  2. execvp()函数实验命令运行
  3. chdir()实现目录切换

三、实验过程

  1. 使用vim进行代码编写
  2. 调试execvp()功能
  3. 实现运行命令功能
  4. 实现日志功能
  5. 实现chdir()功能

四、实验结果

QQ图片20220428212511

QQ图片20220428212519

五、问题总结

  1. 命令字符串最后一个应该为NULL
  2. 不要忘记malloc空间

六、源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <malloc.h>

#define MAX_LINE 80
typedef struct history{
char args[20][20];//命令
int argc;//命令个数
}history;
int main(){
history History[20];
char tempOrder[MAX_LINE][MAX_LINE];
int historyNumber = 0;//命令的数量
memset(tempOrder, 0, sizeof(tempOrder));
while(1){
printf("osh>");
char c;
int i=0;
char *order[20];//运行命令
do{
order[i]=(char *)malloc(10*sizeof(char));
scanf("%s",order[i]);//读入命令
scanf("%c",&c);
i++;
}while( c!= '\n');
order[i]=(char *)malloc(10*sizeof(char));
order[i]=NULL;
if(strcmp(order[0],"!!")==0){
if(historyNumber==0) { printf("History is empty");continue; }
for (int j = 0; j < History[historyNumber-1].argc; ++j) {
order[j]=(char *)malloc(10*sizeof(char));
strcpy(order[j],History[historyNumber-1].args[j]);
}
} else if(strcmp(order[0],"!")==0){
if(i==1) {printf("please input number");continue;}
int number=order[1][0]-'0'-1;
if(number>historyNumber||number<0){ printf("number is illegal");continue;}
for (int j = 0; j < History[historyNumber-1].argc; ++j) {
order[j]=(char *)malloc(10*sizeof(char));
strcpy(order[j],History[number].args[j]);
}
}else if(strcmp(order[0],"exit")==0){
printf("bye\n");//退出程序
break;
}
History[historyNumber].argc=i;//记录这个命令有几行
for (int j = 0; j < i; ++j) {
strcpy(History[historyNumber].args[j],order[j]);
}
historyNumber++;

if(strcmp(order[0],"cd")==0){
if(chdir(order[1])==-1){
printf("Error\n");
continue;
}else{
printf("you are in %s\n",order[1]);
}
}

pid_t pid;
if((pid = fork()) == -1) { printf("Fork Error.\n"); }
if(pid == 0) {
execvp(order[0], order);
break;
}
wait(-1);
}
return 0;
}