课设一 编写一个小型命令处理器smallshell

 

目标

一、目标
设计并实现一个简单的命令处理程序,名字为smallshell。要求具备以下基本功能:
1.支持交互式的用户界面
2.支持5条以上的内置命令:cd,exit,ls,cp,pwd等。
3.支持可执行文件的运行
4.支持输入输出重定向功能
5.支持管道功能

linux文件结构

struct dirent {
       ino_t          d_ino;         /* 索引值 */
       off_t          d_off;         /* 相对于下一个目录的偏移*/
       unsigned short d_reclen;      /* 记录的长度 */
       unsigned char  d_type;        /* 文件类型 */
       char           d_name[256];   /* 文件名 */
};

代码

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>

#define NAMELEN 100

int main() {
	char *gpath;
	while (1) {
		char *username = getlogin();
		
		char *path;
		char mOper[NAMELEN];
		char mText[NAMELEN];

		char servername[NAMELEN], pathname[NAMELEN];
		if (gethostname(servername, NAMELEN) == -1) {
			printf("get hostname wrong");
			break;
		}

		path = getcwd(pathname, NAMELEN);


		printf("%s @ %s : %s :", username, servername, pathname);

		//fgets(mText, 100, stdin);
		scanf("%s", mOper);

		if (strcmp(mOper, "cd") == 0) {
			scanf("%s", mText);
			if (chdir(mText) == -1) {
				printf("Catalog invalid!");
			}
		}
		else if (strcmp(mOper, "exit") == 0) {
			exit(EXIT_SUCCESS);
		}
		else if (strcmp(mOper, "path") == 0) {
			strcpy(gpath,mText);
		}
		else if (strcmp(mOper, "ls") == 0) {
			DIR *dir_ptr;
			struct dirent *direntp;

			if ((dir_ptr = opendir(pathname)) == NULL)
				fprintf(stderr, "ls1:cannot open %s\n", pathname);
			else
			{
				while ((direntp = readdir(dir_ptr)) != NULL && strcmp(direntp->d_name, ".") != 0 \
					&& strcmp(direntp->d_name, "..") != 0)
					printf("%s\n", direntp->d_name);
				closedir(dir_ptr);
			}
		}
		else if(access(mOper,X_OK)==0){

			int fd[2];
			pipe(fd);
			pid_t fpid = fork();
			if (fpid < 0) 
				printf("Process creation failure");
			else if (fpid == 0) {
				char* envp = {pathname,0};
				execve(mOper,NULL,envp );


				close(fd[1]);
				dup2(fd[0], 0);

				fid = open(mOper, O_WRONLY | O_CREAT);
				dup2(fid,0);
				dup2(fid,1);
			}
			else {
				close(fd[2]);
				dup2(fd[1], 1);
			}
		}
		else {
			printf("Invalid input.please input again.");
		}
						

	}
	return 0;
}
posted @ 2020-07-04 16:37  treblez  阅读(755)  评论(0编辑  收藏  举报