execvp 找不到程序时返回错误

returning error when execvp does not find program

int spawn( char* program, char** args) {

pid_t child_pid;
child_pid = fork(); 

if( child_pid > 0) {  /
        wait(NULL);
        return (int)child_pid;
}

else {
    if(execvp(program, args) == -1){
        exit(EXIT_FAILURE); 
    }
    return (int)child_pid; 
    }
}

我知道这段代码有点乱,但请耐心等待:我正在尝试创建自己的 shell。这是将启动一个新的子进程并执行代码的函数。但是,当我输入字符串时,我无法 return 出错。

例如,如果我键入 'heyman',我只会返回 'heyman',而我想返回某种错误('heyman' 不是命令)。

我希望出口(EXIT_FAILURE)能做到这一点,但它没有。如果有人能在这里帮助我,我将不胜感激

使用perror()报错

if (execvp(program, args) == -1) {
    perror("execvp");
    exit(EXIT_FAILURE);
}

不需要在子函数中使用return (int)child_pid。如果execvp()成功,则运行后的代码none;失败则报错退出