c - 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.
解决方案
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).
推荐阅读
- disassembly - 在 IDAPython 中处理名称
- excel - 如何显示错误信息和停止宏
- java - java jackson XML - 解析时如何忽略外包装?
- javascript - 在每秒的确切开始处(或每秒特定的毫秒数)运行一个函数
- java - Cucumber - 如何构建你的测试步骤?
- c# - 如何实现全局 WinAPI 覆盖接口
- html - 使用 Doxygen 内联显示图像
- visual-studio-code - 当窗格中的最后一个文件关闭时,防止 Visual Studio Code 更改窗口布局?
- php - php,如何作为类连接数据库,发送sql语句并返回结果
- node.js - 如何用 Sequelize 建立两个不直接相互依赖的表之间的关系?