C - 分叉进程总是返回 > 0 我不知道为什么?



你好,我正在用C创建一个简单的shell,目前我有一个问题,因为它似乎总是返回一个值>0,即使我输入一些非Linux命令,如"ehshhduh"它仍然会打印出"智利进程完成";而不是返回一个错误消息,有人可以解释给我我做错了,谢谢?

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

char str_tokens[50];
char * get_input() {
pid_t pid; 
char *tokens[30][50];
char input[512];
char *charp;
char *burner[20];

int i = 0;
while(true) {
printf(">");
if(fgets(input, 512, stdin) == 0 || strncmp(input, "exit", 4) == 0) {    /* reads in input from user no more than 512 chars including null terminator, program terminates if "exit" or CTRL-D is detected*/
printf("exitting program");
exit(0);
} 
const char delimiters[9] = {'&', ';', 'n', '|', ' ', 't', '>', '<',}; 
charp = strtok(input, delimiters); /* splits the string on delimiters */
while (charp != NULL) {

strcpy(str_tokens, charp);
charp = strtok(NULL, delimiters);   // sets the char pointer to null
//after each split of the string 
//so the loop eventually terminates */
} 
char *args[] = {str_tokens, 0};  
pid = fork();     // fork a child process
if (pid == -1) { /* error occured */
fprintf(stderr, "Error occured with Fork");
return 1;
}
else if (pid > 0) {  /* parent process */
/* parent will wait for the child process to complete */
wait(NULL);
printf("Child process completed") ;
}
else if(pid == 0){ // (pid == 0)  /* this is the child process */
execvp(args[0], args);          /* first param the file path, seconf is null terminated array of char pointers*/
printf("this is the child process");
_exit(EXIT_FAILURE);            /* in the case our exec never returns exit */
}

}

return str_tokens;
}

void run_external(char* commands[50]) {
commands = get_input();
}
int main () {
run_external(get_input());
return(0);

}

fork的调用发生在在新程序中调用execvp之前

首先创建一个新进程,然后当您成功完成后,尝试在该进程中启动一个新程序。如果程序名无效,则execvp返回子进程,_exit返回子进程。

同样,当forkexecvp失败时,您应该调用perror。这将打印一条错误消息,说明原因。

相关内容

最新更新