0

我阅读了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”

4

2 回答 2

1

sh -c nosuchcommand本身返回 127。它是具有特殊含义的返回码之一。

所以我认为你没有看到 execl 在这种情况下实际返回。

于 2017-09-06T08:06:11.937 回答
1

它不“知道”。它只是执行您告诉它的内容。/bin/sh然后报告它找不到它,然后/bin/sh以非零退出代码退出,在这种情况下127

另请注意,您不能完全依赖于它的返回,127因为它是特定于 shell 的。一些 shell(包括/bin/sh在某些操作系统上)将1改为返回。

于 2017-09-06T08:07:01.903 回答