2011-08-09 3 views
0

나는 학습을 위해 C로 셸을 만들고 있는데, 지금까지는 fgets()를 통해 문자열을 입력 할 수있는 시점에 문자열을 "청크"로 분류 한 다음이 청크를 execlp()에 전달되었습니다. 첫 번째 청크는 명령의 이름이고 이후의 청크는 명령 인수가됩니다.C 프로그래밍 - execlp() 도움이?

execlp() 호출을 제외한 모든 기능이 정상적으로 작동합니다. 그러나 내가 잘못하고있는 것을 보지 못한다.이 모든 것은 man 페이지에 의하면 나에게 합당한 것처럼 보인다.

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 

#define MAX_CHUNKS 10 

/*========================================================================== 
* Given a string, Break it down into chunks. Separated by ' ', skipping \n 
* ========================================================================*/ 
int break_down_string(char *input_string, char *pointer_array[MAX_CHUNKS]) 
{ 
     char *p = input_string, buffer[100]={0};//Initialize buffer to zero's. 
     short int index = 0, space_count = 0, i; 


    strncat(p, " ", 1); 

    while (*p != '\0') 
    { 
     if (index == MAX_CHUNKS) break; //End if MAX_CHUNKS chunks taken from string. 
     if (*p == '\n'){ //Skip newline characters. 
      p++; 
      continue; 
      } 

     if (*p == ' ') //Space Detected 
     { 
      if (space_count == 0) 
      { 
       pointer_array[index] = (char *)malloc(sizeof(char) * strlen(buffer) +1); 
       strncpy(pointer_array[index], buffer, strlen(buffer)); 
       strncat(pointer_array[index], "\0", 1); 
       bzero(buffer, sizeof(buffer)); 
       index++; 
      } 
      space_count = 1; 
     } 
     else //Non-Space Detected 
     { 
      if (space_count > 0) space_count = 0; 
      strncat(buffer, p, 1); 
     } 
     p++; 
    } 

pointer_array[index] = NULL; //Set end pointer to NULL for execlp(). 

return 0; 
} 



/*--------------------------------MAIN()-----------------------------------*/ 
int main(void) 
{ 
    char buffer[100]; 
    char *pointer_array[MAX_CHUNKS]; //Array which will hold string chunks 

    fgets(buffer, sizeof(buffer), stdin); 

    break_down_string(buffer, pointer_array); 

    if (fork() == 0) 
    { 
     printf("Child process!\n"); 
     execlp(pointer_array[0], (pointer_array+1), NULL); 
    } 
    else 
    { 
     printf("Parent process!\n"); 
    } 

return 0; 
} 

도움을 주시면 정말 고맙겠습니다.

+0

때 execlp 제대로하지 않는 작업은 무엇입니까? –

+0

SO에서 물어 보는 것이 더 쉽고'execlp' 함수의 리턴 코드를 체크하지 않습니까? :) –

답변

2

이 잘되지 않습니다 :

char *pointer_array[MAX_CHUNKS]; 
execlp(pointer_array[0], (pointer_array+1), NULL); 

때 execlp는 int execlp(const char *file, const char *arg, ...);로 선언된다. 경고는 char *이 예상되는 곳에 char **을 전달할 수 없다는 것을 분명히해야합니다.


개인적으로 나는 매우 강하게 execvp을 선호합니다. 또한 새로운 프로세스에 많은 인수를 전달할 수 있습니다.

/* Make sure the last element of pointer_array is NULL. */ 
execvp(pointer_array[0], pointer_array); 

또한 시도 할 수 :

execlp(pointer_array[0], pointer_array[1], NULL); 
+0

Woaaah, 감사합니다! 비교에서 execvp는 사용하기가 매우 쉽습니다! .. 아마도 execlp()를 사용하는 것을 잊어 버릴 것입니다. –

+0

execlp에서 argv [0]을 벗어납니다. 'execlp (pointer_array [0], pointer_array [0], pointer_array [1], NULL)'이어야합니다. – Dave

관련 문제