为什么我们在`execlp`中重复声明可执行文件的名称? [英] Why do we double state the executable name in `execlp`?

查看:86
本文介绍了为什么我们在`execlp`中重复声明可执行文件的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们要使用 execlp 运行命令

execlp("ps", "ps", NULL);

在这里可以看到冗余,因为我们两次通过了 ps .此行为在所有 exec 变体中都是一致的.

A redundancy can be seen here, since we pass ps twice. This behavior is consistent across all exec variants.

为什么执行人员需要这种冗余?为什么不写它,以便我们可以简单地

Why does exec want such redundancy? Why isn't it written so that we can simply

execlp("ps", NULL);

推荐答案

其他答案已说明您可以提供与程序名称不同的 argv [0] ,但未说明为什么,您可能想要这样做.

Other answers have explained that you may provide a different argv[0] than the name of the program, but haven't explained why you might want to do this.

某些程序的行为会有所不同,具体取决于调用它们的名称.常见的例子是贝壳,例如 sh bash csh .他们检查 argv [0] 的第一个字符,如果这是-,则它们将作为登录shell而不是常规shell.因此,当/bin/login 调用用户的登录shell时,它会执行以下操作:

Some programs behave differently depending on the name that's used to invoke them. A common example is shells, e.g. sh, bash, and csh. They check the first character of argv[0], and if this is - they operate as a login shell rather than a regular shell. So when /bin/login is invoking the user's login shell, it does something like:

execlp("/bin/bash", "-bash", (char*)NULL);

通过这种方式, bash 知道它是作为登录名运行的,并且可以相应地运行.可以使用option参数来完成此操作,但是每个可能用作登录shell的程序都必须识别该选项(某些特殊的用户名具有的登录shell并不是真正的shell,而是其他程序,并且需要它们支持与真实shell相同的选项可能会有问题).

This way, bash knows that it's being run as part of a login and can behave accordingly. This could have been done using an option parameter, but then every program that might be used as a login shell would have to recognize that option (some special usernames have login shells that aren't really shells, but are other programs, and requiring them to support the same option as real shells might be problematic).

这篇关于为什么我们在`execlp`中重复声明可执行文件的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆