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

为何fopen()打开/dev/null失败而open()可成功?

问题:Godbolt平台上fopen写入/dev/null失败,open以O_WRONLY打开成功

在Godbolt平台运行代码时,发现调用fopen("/dev/null", "w")会失败,但调用open("/dev/null", O_WRONLY)却能成功,测试代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    if (fopen("/dev/null", "w") == NULL) {
        perror("fopen");
    }
    if (open("/dev/null", O_WRONLY) == -1) {
        perror("open");
    }
}

原因分析

这是由于Godbolt的沙箱执行环境对标准IO库(stdio)做了特殊限制,而底层系统调用open不受该限制影响:

  • Godbolt的沙箱可能通过钩子或修改stdio库的方式,限制了其可以访问的文件路径或文件操作权限,导致fopen无法正常打开/dev/null;
  • open是直接调用内核的系统调用接口,沙箱对系统调用的权限规则设计更宽松,允许访问/dev/null这类特殊设备文件,因此可以成功打开。

补充:提问者已针对该问题向Godbolt提交了bug报告。

内容的提问来源于stack exchange,提问作者Chris_F

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:04:53