为什么argv参数execvp不是const?

Jon*_*yer 26 c libc execvp

因此定义了execvp:

int execvp(const char *file, char *const argv[]);
Run Code Online (Sandbox Code Playgroud)

这使得这样的代码无法使用:

const char* argv[] = {"/bin/my", "command", "here", NULL};
execvp(argv[0], argv);
Run Code Online (Sandbox Code Playgroud)

这是意外遗漏吗?围绕这个const_cast是否安全?或者做一些execvp实现实际上是在那个内存上乱写?

Mic*_*urr 8

POSIX规范说(http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html):

的argv[]和envp[]指针和字符串数组到这些阵列点不得通过调用修改以exec函数之一,除非更换处理图像的结果.

我认为缺失(或错位)const只是一个历史怪异.

  • 缺少的"常量"不是历史的奇怪之处; 更确切地说,这是因为你不能在没有强制转换的情况下从C中的`char**'转换为`const char*const*`(但你可以*在C++中). (6认同)
  • @Adam:对.这就是帖子中第一个问题的答案.我间隔一点:http://c-faq.com/ansi/constmismatch.html (2认同)
  • 另请参阅exec的POSIX规范末尾的RATIONALE部分.它解释了遗漏的选择. (2认同)