首页 > 解决方案 > execvp() return value if path is wrong

问题描述

I am currently writing a custom shell script in C. In order to execute the command, I use the execvp() function. For example:

if((execvp(args[0], args)) == -1) //args is a char **array containing the commands arguments
{
    printf("ERROR: Wrong command\n");
    exit(EXIT_FAILURE);
}

The thing is, when 2 commands are separated by "&&", if the first one is not executed (thus, execvp will return -1) the whole process must break before we go to the next one. It works totally fine, if for example I write " <some random wrong command> && ls ".

Although, if I write something like " ls <some random wrong path> && ls ", execvp() will be executed normally, and print the message:

ls: cannot access '...': No such file or directory

Then it will go to the next command. Apparently, in that case execvp() doesn't return -1.

Is there any other value that execvp() returns in that case? If not, how can I check if the path exists before executing the command?

EDIT I just check the value of status (generated by wait(&status) while the parent waits for the child to terminate). If it is non-zero, then it means that the command was not executed.

标签: cshellexecvp

解决方案


Is there any other value that execvp() returns in that case?

execvp doesn't return any value in this case, because it succeeded in running the command you asked it to. You couldn't get an error from ls unless ls had been successfully execed. You probably meant for your && to short-circuit not only on exec failure, but also on a successful exec where the exec'd process returns a nonzero status code (as indicated by wait / waitpid).

If not, how can I check if the path exists before executing the command?

Generally speaking, this doesn't make any sense. It's not normal for a shell to make assumptions about how the commands it's running will interpret their arguments, e.g. that one of them should be the name of an existing file. Even if you did have such a special case, it would be subject to a race condition (the file exists when the shell checks but not when ls runs, or vice versa).


推荐阅读