我读到了 APUE 3rd , 8.13, system Function,看到了一个没有信号处理的system function实现版本,代码如下:
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
int system(const char *cmdstring) /* version without signal handling */
{
pid_t pid;
int status;
if (cmdstring == NULL)
return(1); /* always a command processor with UNIX */
if ((pid = fork()) < 0) {
status = -1; /* probably out of processes */
} else if (pid == 0) { /* child */
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); /* execl error */
} else { /* parent */
while (waitpid(pid, &status, 0) < 0) {
if (errno != EINTR) {
status = -1; /* error other than EINTR from waitpid() */
break;
}
}
}
return(status);
}
测试该版本系统功能的代码如下:
int main(void)
{
int status;
if ((status = system("date")) < 0)
err_sys("system() error");
pr_exit(status);
if ((status = system("nosuchcommand")) < 0)
err_sys("system() error");
pr_exit(status);
if ((status = system("who; exit 44")) < 0)
err_sys("system() error");
pr_exit(status);
exit(0);
}
测试代码结果如图所示(看不懂的可以忽略结果中的中文): 我想知道如果将对/bin/sh 无效的“nosuchcommand”提供给/bin/sh,为什么execl 会返回。在我看来,execl只是替换当前进程的代码,然后从入口点运行,即使“nosuchcommand”对/bin/sh无效,它与execl无关,但与/bin/sh无关。那么,execl 是如何知道“nosuchcommand”对于/bin/sh 执行并返回无效的呢? execl 是否通过在执行/bin/sh 之前检查提供给/bin/sh 的命令来区别对待/bin/sh 以便它提前知道提供给/bin/sh 的无效参数?我知道 execl 不会以不同方式对待/bin/sh,那么,execl 怎么知道“nosuchcommand”对/bin/sh 执行和返回无效?
最佳答案
sh -c nosuchcommand
本身返回 127。它是其中之一 return codes with a special meaning .
所以我认为在这种情况下您没有看到 execl 实际上返回。
关于linux - Linux中execl如何处理 "/bin/sh"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46069789/