Chinaunix

标题: 请大家看个Unix /linux 编程实践上的例子 [打印本页]

作者: hmchzb19    时间: 2016-01-18 15:12
标题: 请大家看个Unix /linux 编程实践上的例子
代码如下:
  1. #include <apue.h>

  2. #define MAXARGS 20
  3. #define ARGLEN 100

  4. int main()
  5. {
  6.     char *arglist[MAXARGS+1];  //an array of ptrs*
  7.     int numargs;                //index into arrays
  8.     char argbuf[ARGLEN];        //read stuff here
  9.     char *makestring();         //malloc etc
  10.     numargs = 0;
  11.     while (numargs < MAXARGS)
  12.     {
  13.         printf("Arg[%d]?",numargs);
  14.         if(fgets(argbuf,ARGLEN,stdin) && *argbuf!='\n')
  15.             arglist[numargs++]=makestring(argbuf);
  16.         else
  17.         {
  18.             if(numargs > 0){
  19.                 arglist[numargs]=NULL;
  20.                 execute(arglist);
  21.                 numargs=0;
  22.                 }
  23.             }
  24.         }
  25.     return 0;
  26.     }


  27. int execute(char *arglist[])
  28. {
  29.     execvp(arglist[0],arglist);
  30.     perror("execvp failed");
  31.     exit(1);
  32.     }

  33. char *makestring(char *buf)
  34. {
  35.     char *cp;

  36.     buf[strlen(buf)-1]='\0';
  37.     cp=malloc(strlen(buf)+1);
  38.     if(cp==NULL){
  39.         fprintf(stderr,"no memory\n");
  40.         exit(1);
  41.         }
  42.     strcpy(cp,buf);
  43.     return cp;
  44.     }
复制代码
说白了就是用exec* 在当前bash 下覆盖,exit退出,应该退出当前bash进程。
但是实际执行的时候不是如此:
  1. [root@ system_program]# ./psh1
  2. Arg[0]?pwd
  3. Arg[1]?
  4. /usr/local/src/c/system_program
  5. [root@ system_program]#
复制代码
这是为什么?
是bash 现在的运行机制吗?

作者: hanzhenlll    时间: 2016-01-18 15:18
没看出有什么结果不对....
作者: yjh777    时间: 2016-01-18 15:31
exec 覆盖的是调用它的进程 ./psh1 , 不是什么当前 bash;

bash 内建命令 exec 才能覆盖自己。你直接 ./psh1 是先 fork() 一个child process,child process 里面再 exec
作者: hmchzb19    时间: 2016-01-18 15:43
LS 说的是啊,我后来才想到 bash 是先fork出psh1 ,然后exec 的。





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2