为何《操作系统:三个简单部分》第5章的exec()系统调用示例代码要使用strdup()?
我正在阅读《操作系统:三个简单部分》(Operating System: Three Easy Pieces)一书,第5章里有一段展示exec()系统调用用法的代码:
#include "common.h" int main(int argc, char ** argv) { printf("hello world (pid: %d)\n", (int) getpid()); int rc = fork(); if (rc < 0) { fprintf(stderr, "fork failed\n"); exit(1); } else if (rc == 0) { printf("hello, I am child (pid: %d)\n", (int) getpid()); char *myargs[3]; myargs[0] = strdup("wc"); myargs[1] = strdup("p3.c"); myargs[2] = NULL; execvp(myargs[0], myargs); // run word count printf("this shouldn't print out\n"); } else { int wc = wait(NULL); printf("hello, I am parent of %d (wc: %d) (pid: %d)\n", rc, wc, (int) getpid()); } return 0; }
我产生了一个疑问:代码里的第12~14行为什么要使用strdup()?我尝试把这部分替换成了下面的代码:
myargs[0] = "wc"; myargs[1] = "p3.c"; myargs[2] = NULL;
替换后程序的运行结果和原代码完全一致,所以我想知道原代码使用strdup()的原因是什么?
Great question! While both approaches work perfectly in this specific case, there are a few key reasons why the original code uses strdup() instead of string literals directly:
Robustness & coding consistency:In real-world scenarios, arguments passed to
execfunctions often aren't hardcoded literals—they might come from user input, dynamically generated strings, or other mutable sources. Usingstrdup()establishes a consistent pattern for handling these cases, so if you later modify the code to use dynamic strings instead of literals, you won't have to rewrite the parameter assignment logic.Potential compatibility with older systems:While POSIX standards don't require
execarguments to point to writable memory, some older system implementations or edge cases might expect the memory to be modifiable (even thoughexecitself won't alter the arguments). String literals live in read-only memory segments (.rodata), whilestrdup()allocates writable heap memory and copies the string there—this avoids any potential compatibility issues with such systems.Educational rigor:As a textbook example, using
strdup()clearly demonstrates the idea of preparing independent memory space forexecarguments. It teaches readers to think about the memory management behind the parameters, rather than just relying on read-only literals which can feel like "magic" without context.
In short, even though both methods work here, strdup() makes the code more generalizable, robust, and aligned with best practices for system-level programming.
内容的提问来源于stack exchange,提问作者wuzirui

