[英]Creating a basic shell in C. Segmentation fault error message
我正在嘗試在 c 中創建 aa basic linux shell。由於某種原因,我收到了 Segmentation fault core dumped 錯誤消息。
我嘗試運行 ls 命令並收到錯誤消息。 幫助將不勝感激。
void execute(char **argv)
{
pid_t pid;
int status;
pid = fork();
if (pid < 0) { /* fork a child process */
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) { /* for the child process: */
if (execvp(*argv, argv) < 0) { /* execute the command */
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else { /* for the parent: */
while (wait(&status) != pid) /* wait for completion */
;
}
}
void main(void)
{
char line[1024]; /* the input line */
char *argv[64]; /* the command line argument */
char *tokens[64];
int numtokens;
while (1) { /* repeat until done .... */
printf("Shell -> "); /* display a prompt */
fgets(line, 64, stdin); /* read in the command line */
printf("\n");
// parse(line, argv);
if ((tokens[0] = strtok(line, " \n\t")) == NULL) continue;
numtokens = 1;
while((tokens[numtokens] = strtok(NULL, " \n\t")) != NULL) numtokens++;
if (strcmp(argv[0], "exit") == 0) /* is it an "exit"? */
exit(0); /* exit if it is */
execute(argv); /* otherwise, execute the command */
}
}
您正在使用argv
的元素,而沒有在main
function 中初始化它們。
您可能想改用tokens
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.