gpt4 book ai didi

c - 为什么 `execvp` 需要一个 `char *const argv[]` ?

转载 作者:太空狗 更新时间:2023-10-29 16:36:20 27 4
gpt4 key购买 nike

我想知道在 const 中两个不同的 exec 函数之间是否存在原因-ness,如果这只是单一 Unix 规范中的一个错误:

摘自 Linux 联机帮助页,似乎与 Single Unix Specification 一致, 这里有两个版本的 exec :

<b>int execlp(const char *</b>file<b>, const char *</b>arg<b>, ...);<br/>
int execvp(const char *</b>file<b>, char *const </b>argv<b>[]);</b>

execlp将其参数作为 const char * , 它需要两个或更多。 const在 C 语言中 promise 该函数不会更改指向的数据,在本例中是构成字符串的实际字符 ( char)。

execvp而是将其参数作为指针数组。但是,不是指向 const char * 的指针数组如您所料,const关键字在不同的位置——这对 C 来说很重要。 execvp是说它可能会修改字符串中的字符,但它 promise 不会修改数组——即指向字符串的指针。所以,换句话说,

int fake_execvp(const char *file, char *const argv[]) {
argv[0] = "some other string"; /* this is an error */
argv[0][0] = 'f'; /* change first letter to 'f': this is perfectly OK! */
/* ⋮ */
}

特别是,这使得使用 C++ 的 std::string 调用 execvp 变得困难(技术上,禁止)的 to_cstr()方法,它返回 const char * .

好像execvp真的应该服用const char *const argv[] ,换句话说,它应该 promise 不进行上述任何更改。

最佳答案

引用您链接的页面:

The statement about argv[] and envp[] being constants is included to make explicit to future writers of language bindings that these objects are completely constant. Due to a limitation of the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of const- qualification for the argv[] and envp[] parameters for the exec functions may seem to be the natural choice, given that these functions do not modify either the array of pointers or the characters to which the function points, but this would disallow existing correct code.

基本上 execlpexecvp 上的 const 限定是完全兼容的,因为它们对相应的参数指定了相同的限制。

关于c - 为什么 `execvp` 需要一个 `char *const argv[]` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com