gpt4 book ai didi

process - 为什么 execve 的 argv 和 envp 参数不指向 const?

转载 作者:太空狗 更新时间:2023-10-29 15:09:16 25 4
gpt4 key购买 nike

例如execve(2),根据 posix,它具有以下原型(prototype) [1]:

int execve(const char *path, char *const argv[], char *const envp[]);

对我来说,好像

int execve(const char *path, const char *const argv[], const char *const envp[]);

会是一个明显的改进。

所以,有人知道为什么会这样吗?什么可以解释需要可能操纵给定的 argv/envp 字符串?

[1] http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html

最佳答案

execve()argvenvp 参数不是指向 const 的指针,以便向后保存与在 const 添加到 C 之前编写的有效 C 代码的兼容性。

C首次出现in 1972 .后来,const 被添加到 C in 1987.

为了保持与 pre-const 代码的兼容性,execve() 的 updated-with-const 声明必须能够接受非 const 输入。 C 不允许从 char *[]const char *[] 的赋值。这可以通过尝试(并且失败)编译以下程序来验证:

void  foo  ( const char * argv[] )  {  return;  }
void main ( int argc, char * argv[] ) { foo ( argv ); }

因此,char *const[] 是向后兼容 pre-const 代码的最严格的类型。

该问题提供了指向 execve() 的 POSIX 文档的链接。链接的 POSIX 文档对此进行了如下解释:

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. ...

实际上,准确地说:不可能以与const 之前的代码向后兼容的方式来陈述这个想法

... 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. Instead, only the array of pointers is noted as constant. The table of assignment compatibility for dst= src derived from the ISO C standard summarizes the compatibility:

        dst:          char *[]   const char *[]   char *const[]   const char *const[]
src:
char *[] VALID - VALID -
const char *[] - VALID - VALID
char * const [] - - VALID -
const char *const[] - - - VALID

Since all existing code ...

意思是在 const 被添加到 C 之前存在的所有代码。

... has a source type matching the first row, the column that gives the most valid combinations is the third column. The only other possibility is the fourth column, but using it would require a cast on the argv or envp arguments. It is unfortunate that the fourth column cannot be used, because the declaration a non-expert would naturally use would be that in the second row.

来源:2018 edition , 2004 edition .

关于process - 为什么 execve 的 argv 和 envp 参数不指向 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26380535/

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