2011-01-20 2 views
1

외부 명령을 실행하기 위해 exec() 또는 변형 중 하나를 사용해야하는 운영 체제 클래스 용 셸을 구축하고 있습니다. 현재 execlp(command,command_parameters, (char *) NULL)을 사용하고 있습니다. 이것은 명령을 잘 실행합니다 (예 : ls은 표준 디렉토리 목록을 반환합니다). 그러나 어떤 파라미터도 구문 분석하지 않는 것 같습니다 (예 : mkdir hello을 실행하면 "hello : missing operand ..."라는 오류가 발생합니다. 'hello --help'를 실행하십시오. . 자세한 내용은) 나는 무엇 실종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. 첫 번째 arg (const char *file 다음)는 실행중인 실행 파일의 이름이며, 호출되는 프로그램에서 이됩니다. 따라서 첫 번째 매개 변수는이를 따라 할 필요가 있습니다.

는 예를 들면 : 당신은 무엇으로

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

, 그것은 좋아하는 일을 :있는 그대로

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

아마, "mkdir", "hello"와 문제의 처리됩니다,하지만 당신은있어 여전히 command_parameters 문자열을 분할하지 않으므로 둘 이상의 인수가있는 명령에 대한 수정 없이는 작동하지 않습니다.

편집 : 추신 귀하의 라인

if (fork < 0) 

if (pid < 0) 
+0

문자 포인터가 NULL로 주조의 의미는 무엇이어야 하는가? –

관련 문제