《Unix/Linux编程实践教程》之Shell编程一


《Unix/Linux编程实践教程》是一本学习系统编程非常好的入门教材。本书第8章开始介绍进程的相关概念。包括相关的命令如ps,以及相关的系统调用如fork,wait等。在本章中,作者通过一步步搭建自己的Shell来讲解unix的进程模型。

《Unix/Linux编程实践教程》之Shell编程一

《Unix/Linux编程实践教程》之Shell编程二

《Unix/Linux编程实践教程》之管道

Unix/Linux编程实践教程【高清PDF中文版+附录光盘+代码】:

为了搭建一个shell,需要学会以下技术:

1)运行一个程序(execvp);

2)建立一个进程(fork);

3)等待退出(wait)。

例子代码如下:

1: /* prompting shell version 1

  2: *        Prompts for the command and its arguments. 
  3: *        Builds the argument vector for the call to execvp. 
  4: *        Uses execvp(), and never returns. 
  5: */ 
  6: 
  7: #include    <stdio.h> 
  8: #include    <signal.h> 
  9: #include    <string.h> 
 10: 
 11: #define    MAXARGS        20                /* cmdline args    */ 
 12: #define    ARGLEN        100                /* token length    */ 
 13: 
 14: int main() 
 15: { 
 16:     char    *arglist[MAXARGS+1];        /* an array of ptrs    */ 
 17:     int    numargs;            /* index into array    */ 
 18:     char    argbuf[ARGLEN];            /* read stuff here    */ 
 19:     char    *makestring();            /* malloc etc        */ 
 20: 
 21:     numargs = 0; 
 22:     while ( numargs < MAXARGS ) 
 23:     {                    
 24:         printf("Arg[%d]? ", numargs); 
 25:         if ( fgets(argbuf, ARGLEN, stdin) && *argbuf != '/n' ) 
 26:             arglist[numargs++] = makestring(argbuf); 
 27:         else 
 28:         { 
 29:             if ( numargs > 0 ){        /* any args?    */ 
 30:                 arglist[numargs]=NULL;    /* close list    */ 
 31:                 execute( arglist );    /* do it    */ 
 32:                 numargs = 0;        /* and reset    */ 
 33:             } 
 34:         } 
 35:     } 
 36:     return 0; 
 37: } 
 38: 
 39: int execute( char *arglist[] ) 
 40: /* 
 41: *    use execvp to do it 
 42: */ 
 43: { 
 44:     execvp(arglist[0], arglist);        /* do it */ 
 45:     perror("execvp failed"); 
 46:     exit(1); 
 47: } 
 48: 
 49: char * makestring( char *buf ) 
 50: /* 
 51: * trim off newline and create storage for the string 
 52: */ 
 53: { 
 54:     char    *cp, *malloc(); 
 55: 
 56:     buf[strlen(buf)-1] = '/0';        /* trim newline    */ 
 57:     cp = malloc( strlen(buf)+1 );        /* get memory    */ 
 58:     if ( cp == NULL ){            /* or die    */ 
 59:         fprintf(stderr,"no memory/n"); 
 60:         exit(1); 
 61:     } 
 62:     strcpy(cp, buf);        /* copy chars    */ 
 63:     return cp;            /* return ptr    */ 
 64: }
 65: 

该程序通过终端接收命令参数, 通过makestring()将'/n’换成'/0',之后存入arglist数组,当输入完成后,在数组最后添加0。最后调用execute()执行。

需要注意的是:如果执行成功,execvp没有返回值,当前程序从进程中清除。

运行后的结果如下:

可以看到,“ls -l” 命令可以成功运行。但存在一个显著的缺陷:程序只能运行一次,不能像一般的shell一样,可以一直等待用户输入,然后执行。

  • 1
  • 2
  • 3
  • 下一页

相关内容