我给参数时execlp doenst工作

时间:2018-11-22 17:37:05

标签: c exec

为什么第一个execlp不起作用,第二个execlp没问题。

int main(){
   int fd[2];
   int i;
   char** arguments = (char**) malloc(5*sizeof(char*));
   char *line = (char*) malloc(15*sizeof(char));
   char *cfile = (char*) malloc(15*sizeof(char));
   char* token;
   size_t bufsize = 0; 

   for(i = 0;i < 5; i++){
      arguments[i] = (char*) malloc(15*sizeof(char));
   }

   getline(&line, &bufsize, stdin);

   i = 0;
   token = strtok(line,TOK_DELIM);
   while( token != NULL ){
      (arguments)[i] = token;
      strcat((arguments)[i++],"\0");
      token = strtok(NULL,TOK_DELIM_1);
   }

   if( !fork() ){
       execlp((arguments)[1],"show",(arguments)[0],NULL);
       close(fd[0]); close(fd[1]);
   }
   close(fd[0]); close(fd[1]);
   waitpid(0,NULL,0);
   if( !fork() ){
      printf("Executable c file:");
      scanf("%s",cfile);
      execlp(cfile,"show",(arguments)[0],NULL);
      close(fd[0]); close(fd[1]);
   }
   close(fd[0]); close(fd[1]);
   waitpid(0,NULL,0);
   return 0;
}

如您所见,cfile和参数都是vuriables(动态char数组)。 要运行该主程序,您必须将显示文件gcc写入gcc -o show show.c 然后,当您运行主程序时,您必须键入(pwd | ./show)pwd是我要执行的命令,而./show我想用来打印pwd输出的可执行文件。我保存了用户的内容进行在线输入,然后解析2d动态数组上的参数。在参数的第一个单元格上(动态2d数组),我保存要执行的命令,第二个保存要运行的可执行文件。 / p>

这是我要使用的显示文件:

int main(int argc, char *argv[]){
char *arg[4];
    printf("Execute commands from other file ...\n");
    arg[0] = "sh";
    arg[1] = "-c";
    arg[2] = argv[1];
    arg[3] = NULL;
    execvp ("/bin/sh", arg);
return 0;

}

并且您必须使用与要在主程序上提供的可执行文件相同的名称来编译它,例如,如果您输入:pwd |。 。/节目 主要,您必须像这样编译显示文件:gcc -o show show.c

还使用这些库:

  • stdlib
  • stdio
  • 不参加
  • 字符串
  • sys /类型
  • errno
  • sys / stat
  • fcntl
  • sys / wait

0 个答案:

没有答案