I'm wondering if there is a reason between two exec functions differing in const
-ness, of if this is just a bug in the Single Unix Spec:
Excerpting from the Linux manpage, which appears to align with the Single Unix Specification, here are a two versions of exec
:
int execlp(const char *file, const char *arg, ...);
int execvp(const char *file, char *const argv[]);
execlp
takes its arguments as const char *
, and it takes two or more of them. const
in C is a promise that the function will not change the pointed-to data, in this case the actual characters (char
) that make up the string.
execvp
instead takes its arguments as an array of pointers. However, instead of an array of pointers to const char *
as you'd expect, the const
keyword is in a different spot—and this matters quite a bit to C. execvp
is saying it may well modify the characters in the strings, but it promises not to modify the array—that is, the pointers to the strings. So, in other words,
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! */
/* ? */
}
In particular, this makes it hard (technically, prohibited) to call execvp using C++'s std::string
's to_cstr()
method, which returns const char *
.
It seems like execvp
really ought to take const char *const argv[]
, in other words, it ought to promise not to do either of the above changes.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…