Linux下用C函数实现简单的交互式shell.doc_第1页
Linux下用C函数实现简单的交互式shell.doc_第2页
Linux下用C函数实现简单的交互式shell.doc_第3页
Linux下用C函数实现简单的交互式shell.doc_第4页
Linux下用C函数实现简单的交互式shell.doc_第5页
已阅读5页,还剩5页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

#include #include #include #include #include #include #include #include #include #define BUF_LEN 1024#define MAX_FILE_NAME 256#define MAX_PROCESS_NUM 2#define MAX_ARGC 10#define BOOL int#define TRUE 1#define FALSE 0#define DELIM |enumE_OPEN = 0,E_PIPE,E_DUP2,E_EXECVP,E_FORK;enumFIRST = 0,SECOND;BOOL get_std_file(char *pos_std, char *std_file)if (!pos_std)return FALSE;*pos_std = 0;*std_file = strtok(pos_std + 1, DELIM);if (*std_file)return TRUE;return FALSE;BOOL get_cmd_args(char *str, char *args)int i = 0;if (!str)return FALSE;if (!(argsi+ = strtok(str, DELIM)return FALSE;while(argsi+ = strtok(NULL, DELIM);return TRUE;int main(int argc, char *argv)char bufBUF_LEN;char *firstMAX_ARGC;char *secondMAX_ARGC;char *stdin_file;char *stdout_file;char *pos;char *pos_stdin;char *pos_stdout;char *pos_pipe;int i;int pfd2;int fd;pid_t pidsMAX_PROCESS_NUM;pid_t pid;while(1)pos_stdin = NULL;pos_stdout = NULL;pos_pipe = NULL;buf0 = 0;printf(akaeducaihui-desktop:%s#, getcwd(buf, BUF_LEN);buf0 = 0;bzero(first, sizeof(first);bzero(second, sizeof(second);if (!(fgets(buf, BUF_LEN, stdin)break;if (buf0 = n | buf0 = 0)continue;pos = strchr(buf, n);if (pos)*pos = 0;if (0 = strcmp(buf, exit)break;pos_pipe = strchr(buf, |);pos_stdin = strchr(buf, );if (pos_pipe)*pos_pipe = |;if (pos_stdin)if (!get_std_file(pos_stdin, &stdin_file)continue;if (pos_stdout)if (!get_std_file(pos_stdout, &stdout_file)continue;if (!get_cmd_args(buf, first)continue;if (pos_pipe)if (!get_cmd_args(pos_pipe + 1, second)continue;if (!pos_pipe)pid = fork();if (0 = pid)if (pos_stdin)fd = open(stdin_file, O_RDONLY);if (fd 0)perror(open failn);exit(E_OPEN);dup2(fd, STDIN_FILENO);if (pos_stdout)fd = open(stdout_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);if (fd 0)perror(open failn);exit(E_OPEN);dup2(fd ,STDOUT_FILENO);execvp(first0, first);perror(execvp failn);exit(E_EXECVP);elsewait(NULL);elseif (pipe(pfd) 0)perror(pipe failn);exit(E_PIPE);pid = getpid();for (i = 0; i 0; i+)pid = fork();if (pid 0)close(pfd0);close(pfd1);for (i = 0; i MAX_PROCESS_NUM; i+)if (pidsi = getpid()switch (i)case FIRST:close(pfd0);if (pos_stdin)fd = open(stdin_file, O_RDONLY);if (fd 0)perror(open failn);exit(E_OPEN);dup2(fd, STDIN_FILENO);execvp(first0, first);perror(execvp failn);exit(E_EXECVP);break;case SECOND:close(pfd1);if (pos_stdout)fd

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论