我阅读了APUE 3rd , 8.13, 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);
}
并且测试代码的结果如图所示(看不懂的就忽略结果中的中文): 我不知道为什么execl会返回如果“nosuchcommand”,对/bin/sh无效,是给/bin/sh。在我看来,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”