2011-01-20 27 views
1

我正在为一个操作系统类构建一个shell,它必须使用exec()或其一个变体来执行外部命令。目前,我正在使用execlp(command,command_parameters, (char *) NULL)。这运行命令就好了(例如ls返回一个标准的目录列表),但似乎没有解析任何参数(例如运行mkdir hello会引发错误“hello:missing operand ...尝试'hello --help'for 。更多信息)我在想什么C execlp()没有正确解析参数字符串

  else // Try to handle an external command 
     { 
      char *command_parameters = malloc(sizeof(raw_command)-sizeof(command)); 
      strcpy(command_parameters, raw_command+strlen(command)+1); 
      pmesg(1, "Command is %s.\n", command); 
      pmesg(1, "The command parameters are %s.\n", command_parameters); 
      pid_t pid = fork(); 
      pmesg(1, "Process forked. ID = %i. \n", pid); 
      int status; 
      if (fork < 0) 
      { 
       printf("Could not fork a process to complete the external command.\n"); 
       exit(EXIT_FAILURE); 
      } 
      if (pid == 0) // This is the child process 
      { 
       pmesg(1, "This is the child process, running execlp.\n"); 
       if (execlp(command, command_parameters, (char *) NULL) < 0) 
       { 
        printf("Could not execute the external command.\n"); 
        exit(EXIT_FAILURE); 
       } 
       else { pmesg(1, "Executed the child process.\n"); } 
      } 
      else {while(wait(&status) != pid); } // Wait for the child to finish executing 
      pmesg(1, "The child has finished executing.\n"); 
     } 

pmesg是一个调试标签,打印)给予一定的调试级别的声明

感谢

回答

3

几个问题在这里?!

  1. execlp(const char *file, const char *arg, ...)需要将参数分开并单独传递,而不是一个大字符串。
  2. 按照惯例,第一个参数(在const char *file之后)是您正在运行的可执行文件的名称,它在被调用的程序中被放入argv[0]。因此,第一个参数需要在此之后。

如:

execlp(command, command, arg1, arg2, ..., (char *)NULL); 

你所拥有的东西,做它喜欢:

execlp(command, command, command_parameters, (char *)NULL); 

可能,原样,照顾你的问题与"mkdir", "hello",但你仍然不会将command_parameters字符串分开,所以如果不修改具有多个参数的命令,它将无法正常工作。

编辑:P.S.你行

if (fork < 0) 

应该

if (pid < 0) 
+0

什么是铸造字符指针为NULL的含义是什么? – 2016-10-14 08:12:05