나는 학습을 위해 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;
}
도움을 주시면 정말 고맙겠습니다.
때 execlp 제대로하지 않는 작업은 무엇입니까? –
SO에서 물어 보는 것이 더 쉽고'execlp' 함수의 리턴 코드를 체크하지 않습니까? :) –