미니 쉘로 Strtok과 execlp
문제
C의 UNIX 프로세스 관리에 더 익숙해지기 위해 미니 쉘을 작성하고 있습니다. CommandLine의 내용을 읽고 EXECLP를 통해 이러한 주장을 시스템으로 전달합니다.
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
#define MAXSIZE 100
char prompt[MAXSIZE];
int main(void)
{
pid_t pid;
printf("> ");
// read stuff
if (fgets(prompt, MAXSIZE, stdin) == NULL){
printf("Input validation error!");
abort();
}
// printf("DEBUG: %s" , prompt);
if (strcmp(prompt, "exit")==0) abort();
if ((pid=fork())<0){ // copy process
printf("Process error!");
abort();
}
if (pid==0){ // exec in son-prcess
char *command=(char*)strtok(prompt, " ");
execlp(command, command, 0); // overwrite memory
printf("Error, command not found!");
abort();
} else {
waitpid(pid, 0, 0);
}
}
사실 이것은 그렇지 않지만, 나는 출력을 얻지 못합니다. execlp()
. 그 이유를 아는 사람이 있습니까?
해결책
나는 당신의 프로그램을 실행하려고 시도했고 실패했기 때문에 실패했습니다 command
포함 된 a \n
(Newline). 나는 넣어서 그것을 변경했다 \n
""대신 strtok
그리고 성공적으로 실행되었습니다.
상세히:
if (pid==0){ // exec in son-prcess
char *command=(char*)strtok(prompt, "\n");
printf ("'%s'\n", command);
execlp (command, command, 0); // overwrite memory
printf("Error %d (%s)\n", errno, strerror (errno));
abort();
} else {
테스트 실행 :
$ ./a.out > ls 'ls' (usual ls behaviour)
다른 팁
Kinopiko는 이미 작동하지 않는 이유를 발견했지만 오류 메시지를 보지 못한 이유는 쉘 프롬프트가이를 덮어 쓰고 있기 때문입니다. 마지막에 Newline을 사용해보십시오.
printf("Error, command not found!\n");
제휴하지 않습니다 StackOverflow