使用execvp()函数需要注意的两点


exec系统调用会从当前进程中把当前程序的机器指令清除,然后在空的进程中载入调用时指定的程序代码,最后运行这个新的程序。

  1. #include<stdio.h>   
  2. #include<signal.h>   
  3. #include<string.h>   
  4. #include<unistd.h>   
  5.   
  6. #define     MAXARGS     (20)   
  7. #define     ARGLEN      (100)   
  8.   
  9. int main()  
  10. {  
  11.     char *arglist[MAXARGS + 1];  
  12.     int numargs;  
  13.     char argbuf[ARGLEN];   
  14.     char *makestring();  
  15.   
  16.     numargs = 0;  
  17.   
  18.     while(numargs < MAXARGS)  
  19.     {  
  20.         printf("Arg[%d]?", numargs);  
  21.         if(fgets(argbuf, ARGLEN, stdin) && *argbuf != '\n')  
  22.             arglist[numargs ++] = makestring(argbuf);  
  23.         else  
  24.         {  
  25.             if(numargs > 0)   
  26.             {  
  27.                 arglist[numargs] = NULL;  
  28.                 execute(arglist);  
  29.                 numargs = 0;  
  30.             }  
  31.         }  
  32.     }  
  33.   
  34.     return 0;  
  35. }  
  36.   
  37. int execute(char* arglist[])  
  38. {  
  39. /* 
  40. *#include<unistd.h>  
  41. *int execlp(const char* file, const char* argv ...) 
  42. * eg. execlp("ps","ps","-au","-x",(char*)0); 
  43. *    1.最后一个参数必须是(char*)0, 如果不强制转换成char*,就会自动转换成int* 有未知的错误。 
  44. *    2.第一个参数是要运行的文件,会在环境变量PATH中查找file. 
  45. *    3.失败会返回-1, 成功无返回值,但是,会在当前进程运行,执行成功后,直接结束当前进程。可以在子进程中运行。 
  46. *    4.第二个参数,是一个参数列表,如同在shell中调用程序一样,参数列表为0,1,2,3……因此,ps作为第0个参数,需要重复一遍 
  47. *    int execvp(const char* file, const char* argv[]);  argv列表最后一个必须是 NULL 
  48. */  
  49.     execvp(arglist[0], arglist);  
  50.     perror("execvp failed");  
  51.     exit(1);  
  52. }  
  53.   
  54. char* makestring(char *buf)  
  55. {  
  56.     char *cp, *malloc();  
  57.   
  58.     buf[strlen(buf) - 1] = '\0';  
  59.     cp = malloc(strlen(buf) + 1);  
  60.   
  61.     if(cp == NULL)  
  62.     {  
  63.         fprintf(stderr, "no memory\n");  
  64.         exit(1);  
  65.     }  
  66.     strcpy(cp, buf);  
  67.     return cp;  
  68. }  

相关内容