为什么argv参数execvp不是const?
因此定义了execvp:
int execvp(const char *file, char *const argv[]);
这使得诸如此类的代码无法使用:
const char* argv[] = {"/bin/my", "command", "here", NULL}; execvp(argv[0], argv);
这是意外遗漏吗? 围绕这个const_cast是否安全? 或者一些execvp实现实际上是在那个内存上涂鸦?
POSIX规范说( http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html ):
argv[]
和envp[]
指针数组以及这些数组指向的字符串不应通过调用其中一个exec函数来修改,除非是替换过程映像。
我认为缺失(或错位)的 const
只是一个历史怪异。
我遇到了同样的情况。 因为execvp()有一个char *const
作为第二个参数,这意味着它接受一个指向char的常量指针。 因此,如果您传递一个指针char,它将能够将指针char转换为指向char的常量指针。 所以,而不是声明它
const char* argv[] = {"/bin/my", "command", "here", NULL};
尝试
char* argv[] = {"/bin/my", "command", "here", NULL};
它会毫无问题地接受argv[]
。