• COMP3511 Spring 2022


    COMP3511 Spring 2022
    PA1: Simplified Linux Shell (Multi-level Pipe)

    /*
        COMP3511 Spring 2022 
        PA1: Simplified Linux Shell (Multi-level Pipe)
    
        Your name:
        Your ITSC email:           @connect.ust.hk 
    
        Declaration:
    
        I declare that I am not involved in plagiarism
        I understand that both parties (i.e., students providing the codes and students copying the codes) will receive 0 marks. 
    
    */
    
    // Note: Necessary header files are included
    // Do not add extra header files
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    // Assume that each command line has at most 256 characters (including NULL)
    #define MAX_CMDLINE_LEN 1024
    #define BUF_SZ 256
    #define TRUE 1
    #define FALSE 0
    
    const char* COMMAND_IN = "<";
    const char* COMMAND_OUT = ">";
    const char* COMMAND_PIPE = "|";
    
    // 内置的状态码
    enum {
    	RESULT_NORMAL,
    	ERROR_FORK,
    	ERROR_COMMAND,
    	ERROR_WRONG_PARAMETER,
    	ERROR_MISS_PARAMETER,
    	ERROR_TOO_MANY_PARAMETER,
    	ERROR_CD,
    	ERROR_SYSTEM,
    	ERROR_EXIT,
    
    	/* 重定向的错误信息 */
    	ERROR_MANY_IN,
    	ERROR_MANY_OUT,
    	ERROR_FILE_NOT_EXIST,
    	
    	/* 管道的错误信息 */
    	ERROR_PIPE,
    	ERROR_PIPE_MISS_PARAMETER
    };
    
    char curPath[BUF_SZ];
    char commands[BUF_SZ][BUF_SZ];
    
    int getCurWorkDir();
    int splitCommands(char command[BUF_SZ]);
    int callExit();
    int callCommand(int commandNum);
    int callCommandWithPipe(int left, int right);
    int callCommandWithRedi(int left, int right);
    
    
    int main() {
    	/* 获取当前工作目录、用户名、主机名 */
    	int result = getCurWorkDir();
    
        char cmdline[MAX_CMDLINE_LEN] ={0};
        char current_absolute_path[MAX_CMDLINE_LEN];
    
    //获取当前目录绝对路径
        if (NULL == getcwd(current_absolute_path, MAX_CMDLINE_LEN))
        {
            exit(-1);
        }
        else
        {
            printf("%s \n",current_absolute_path);
        }
    
        //fgets(cmdline, MAX_CMDLINE_LEN, stdin);
        int fd, size;
        strcat(current_absolute_path, "/sampleinput/in07.txt");
        fd = open(current_absolute_path, O_RDONLY);
        if(fd==-1){
            printf("can not open the file\n");
            exit(-1);
        }
        else
        {
            printf("%s \n",current_absolute_path);
        }
        int len=read(fd, cmdline, MAX_CMDLINE_LEN);
        printf("%s\n",cmdline);
        close(fd);
    
        int commandNum = splitCommands(cmdline);
        if (commandNum != 0) { // 用户有输入指令
            result = callCommand(commandNum);
            switch (result) {
                case ERROR_FORK:
                    fprintf(stderr, "\e[31;1mError: Fork error.\n\e[0m");
                    exit(ERROR_FORK);
                case ERROR_COMMAND:
                    fprintf(stderr, "\e[31;1mError: Command not exist in myshell.\n\e[0m");
                    break;
                case ERROR_MANY_IN:
                    fprintf(stderr, "\e[31;1mError: Too many redirection symbol \"%s\".\n\e[0m", COMMAND_IN);
                    break;
                case ERROR_MANY_OUT:
                    fprintf(stderr, "\e[31;1mError: Too many redirection symbol \"%s\".\n\e[0m", COMMAND_OUT);
                    break;
                case ERROR_FILE_NOT_EXIST:
                    fprintf(stderr, "\e[31;1mError: Input redirection file not exist.\n\e[0m");
                    break;
                case ERROR_MISS_PARAMETER:
                    fprintf(stderr, "\e[31;1mError: Miss redirect file parameters.\n\e[0m");
                    break;
                case ERROR_PIPE:
                    fprintf(stderr, "\e[31;1mError: Open pipe error.\n\e[0m");
                    break;
                case ERROR_PIPE_MISS_PARAMETER:
                    fprintf(stderr, "\e[31;1mError: Miss pipe parameters.\n\e[0m");
                    break;
            }
        }
    	
    }
    
    int getCurWorkDir() { // 获取当前的工作目录
    	char* result = getcwd(curPath, BUF_SZ);
    	if (result == NULL)
    		return ERROR_SYSTEM;
    	else return RESULT_NORMAL;
    }
    
    int splitCommands(char command[BUF_SZ]) { // 以空格分割命令, 返回分割得到的字符串个数
    	int num = 0;
    	int i, j;
    	int len = strlen(command);
    
    	for (i=0, j=0; i<len; ++i) {
    		if (command[i] != ' ') {
    			commands[num][j++] = command[i];
    		} else {
    			if (j != 0) {
    				commands[num][j] = '\0';
    				++num;
    				j = 0;
    			}
    		}
    	}
    	if (j != 0) {
    		commands[num][j] = '\0';
    		++num;
    	}
    
    	return num;
    }
    
    int callExit() { // 发送terminal信号退出进程
    	pid_t pid = getpid();
    	if (kill(pid, SIGTERM) == -1) 
    		return ERROR_EXIT;
    	else return RESULT_NORMAL;
    }
    
    int callCommand(int commandNum) { // 给用户使用的函数,用以执行用户输入的命令
    	pid_t pid = fork();
    	if (pid == -1) {
    		return ERROR_FORK;
    	} else if (pid == 0) {
    		/* 获取标准输入、输出的文件标识符 */
    		int inFds = dup(STDIN_FILENO);
    		int outFds = dup(STDOUT_FILENO);
    
    		int result = callCommandWithPipe(0, commandNum);
    		
    		/* 还原标准输入、输出重定向 */
    		dup2(inFds, STDIN_FILENO);
    		dup2(outFds, STDOUT_FILENO);
    		exit(result);
    	} else {
    		int status;
    		waitpid(pid, &status, 0);
    		return WEXITSTATUS(status);
    	}
    }
    
    int callCommandWithPipe(int left, int right) { // 所要执行的指令区间[left, right),可能含有管道
    	if (left >= right) return RESULT_NORMAL;
    	/* 判断是否有管道命令 */
    	int pipeIdx = -1;
    	for (int i=left; i<right; ++i) {
    		if (strcmp(commands[i], COMMAND_PIPE) == 0) {
    			pipeIdx = i;
    			break;
    		}
    	}
    	if (pipeIdx == -1) { // 不含有管道命令
    		return callCommandWithRedi(left, right);
    	} else if (pipeIdx+1 == right) { // 管道命令'|'后续没有指令,参数缺失
    		return ERROR_PIPE_MISS_PARAMETER;
    	}
    
    	/* 执行命令 */
    	int fds[2];
    	if (pipe(fds) == -1) {
    		return ERROR_PIPE;
    	}
    	int result = RESULT_NORMAL;
    	pid_t pid = vfork();
    	if (pid == -1) {
    		result = ERROR_FORK;
    	} else if (pid == 0) { // 子进程执行单个命令
    		close(fds[0]);
    		dup2(fds[1], STDOUT_FILENO); // 将标准输出重定向到fds[1]
    		close(fds[1]);
    		
    		result = callCommandWithRedi(left, pipeIdx);
    		exit(result);
    	} else { // 父进程递归执行后续命令
    		int status;
    		waitpid(pid, &status, 0);
    		int exitCode = WEXITSTATUS(status);
    		
    		if (exitCode != RESULT_NORMAL) { // 子进程的指令没有正常退出,打印错误信息
    			char info[4096] = {0};
    			char line[BUF_SZ];
    			close(fds[1]);
    			dup2(fds[0], STDIN_FILENO); // 将标准输入重定向到fds[0]
    			close(fds[0]);
    			while(fgets(line, BUF_SZ, stdin) != NULL) { // 读取子进程的错误信息
    				strcat(info, line);
    			}
    			printf("%s", info); // 打印错误信息
    			
    			result = exitCode;
    		} else if (pipeIdx+1 < right){
    			close(fds[1]);
    			dup2(fds[0], STDIN_FILENO); // 将标准输入重定向到fds[0]
    			close(fds[0]);
    			result = callCommandWithPipe(pipeIdx+1, right); // 递归执行后续指令
    		}
    	}
    
    	return result;
    }
    
    int callCommandWithRedi(int left, int right) { // 所要执行的指令区间[left, right),不含管道,可能含有重定向
    	// if (!isCommandExist(commands[left])) { // 指令不存在
    	// 	return ERROR_COMMAND;
    	// }	
    
    	/* 判断是否有重定向 */
    	int inNum = 0, outNum = 0;
    	char *inFile = NULL, *outFile = "text";
    	int endIdx = right; // 指令在重定向前的终止下标
    
    	for (int i=left; i<right; ++i) {
    		if (strcmp(commands[i], COMMAND_IN) == 0) { // 输入重定向
    			++inNum;
    			if (i+1 < right)
    				inFile = commands[i+1];
    			else return ERROR_MISS_PARAMETER; // 重定向符号后缺少文件名
    
    			if (endIdx == right) endIdx = i;
    		} else if (strcmp(commands[i], COMMAND_OUT) == 0) { // 输出重定向
    			++outNum;
    			if (i+1 < right)
    				outFile = commands[i+1];
    			else return ERROR_MISS_PARAMETER; // 重定向符号后缺少文件名
    				
    			if (endIdx == right) endIdx = i;
    		}
    	}
    	/* 处理重定向 */
    	if (inNum == 1) {
    		FILE* fp = fopen(inFile, "r");
    		if (fp == NULL) // 输入重定向文件不存在
    			return ERROR_FILE_NOT_EXIST;
    		
    		fclose(fp);
    	}
    	
    	if (inNum > 1) { // 输入重定向符超过一个
    		return ERROR_MANY_IN;
    	} else if (outNum > 1) { // 输出重定向符超过一个
    		return ERROR_MANY_OUT;
    	}
    
    	int result = RESULT_NORMAL;
    	pid_t pid = vfork();
    	if (pid == -1) {
    		result = ERROR_FORK;
    	} else if (pid == 0) {
    		/* 输入输出重定向 */
    		if (inNum == 1)
    			freopen(inFile, "r", stdin);
    		if (outNum == 1)
    			freopen(outFile, "w", stdout);
    
    		/* 执行命令 */
    		char* comm[BUF_SZ];
    		for (int i=left; i<endIdx; ++i)
    			comm[i] = commands[i];
    		comm[endIdx] = NULL;
    		execvp(comm[left], comm+left);
    		exit(errno); // 执行出错,返回errno
    	} else {
    		int status;
    		waitpid(pid, &status, 0);
    		int err = WEXITSTATUS(status); // 读取子进程的返回码
    
    		if (err) { // 返回码不为0,意味着子进程执行出错,用红色字体打印出错信息
    			printf("\e[31;1mError: %s\n\e[0m", strerror(err));
    		}
    	}
    	return result;
    }
    
    • 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
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
  • 相关阅读:
    5G网络助力智慧文旅发展:实现旅游资源的优化配置与高效利用
    [交互]接口与路由问题
    vue2中,下拉框多选和全选的实现
    QT 之LineEdit设置
    docker部署 spring-boot 项目,验证码获取报错的解决方法
    【PMP考前冲刺题-第二小节(2022.7)】解析
    数据结构PT1——线性表/链表
    MySQL之搭建主从复制
    【永艺XY椅】试用体验
    【HTML+CSS】实现网页的导航栏和下拉菜单
  • 原文地址:https://blog.csdn.net/wwws1994/article/details/123538812