linux - Linux中execl如何处理 "/bin/sh"?

标签 linux bash shell system-calls execl

我读到了 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);
}

测试代码结果如图所示(看不懂的可以忽略结果中的中文): test code result 我想知道如果将对/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/

相关文章:

python - 抓取终端的输出

root shell "#"和 "sh-4.2 #"之间的 Linux 区别

c - 替换 XKeycodeToKeysym

linux - 如何使用免费的 Windows 堆栈在 Amazon AWS 免费层上使用 XAMPP 部署 Windows 开发的应用程序?

c - 管道的 self 实现,如何知道有多少进程对我的管道有文件描述符?

ruby-on-rails - 保持 rake 作业运行

bash - 找不到 sed 命令

linux - bash中有 "goto"语句吗?

python - 更改 python 3.3.2 中的 shell 打印颜色

linux - 使用linux根据修改日期创建jpg图像的时间轴