You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何《操作系统:三个简单部分》第5章的exec()系统调用示例代码要使用strdup()?

为什么在execvp()的参数数组中使用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 exec functions often aren't hardcoded literals—they might come from user input, dynamically generated strings, or other mutable sources. Using strdup() 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 exec arguments to point to writable memory, some older system implementations or edge cases might expect the memory to be modifiable (even though exec itself won't alter the arguments). String literals live in read-only memory segments (.rodata), while strdup() 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 for exec arguments. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:23:12