Why is argv parameter to execvp not const?

2020-05-24 20:52发布

execvp is defined thus:

int execvp(const char *file, char *const argv[]);

Which precludes code such as this from being used:

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

Was this an accidental omission? Is it safe to const_cast around this? Or do some execvp implementations actually scribble on that memory?

标签: c libc execvp
2条回答
虎瘦雄心在
2楼-- · 2020-05-24 21:12

I came across this same situation. Because execvp() has a char *const as the second parameter, that means it accepts a constant pointer to a char. Therefore, if you pass it a pointer char it will be able to cast the pointer char to a constant pointer to a char. So, instead of declaring it

const char* argv[] = {"/bin/my", "command", "here", NULL};

try

char* argv[] = {"/bin/my", "command", "here", NULL};

and it will accept argv[] without issue.

查看更多
做自己的国王
3楼-- · 2020-05-24 21:32

The POSIX spec says (http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html):

The argv[] and envp[] arrays of pointers and the strings to which those arrays point shall not be modified by a call to one of the exec functions, except as a consequence of replacing the process image.

I think the missing (or misplaced) const is simply an historical oddity.

查看更多
登录 后发表回答