c - 为什么我不能 "freopen"和 "tmpfile"?

标签 c docker temporary-files

我尝试编译并运行包含以下几行的 C 代码:

FILE *preproc_producer = NULL;
preproc_producer = tmpfile();
// preproc_producer is not NULL here
preproc_producer = freopen(NULL, "r+", preproc_producer);
// preproc_producer is NULL here

但是,在运行代码时,preproc_ Producer 最终为NULL,错误代码为Stale NFS file handle

  1. 上面的代码有什么问题?

  2. 此处调用 freopen 的目的是什么?我注释掉了 freopen 行,程序的其余部分似乎正在工作。

我正在使用 GCC 4.7.2,在 Docker 0.6.7 Linux 容器中运行 Ubuntu 64 12.04。上面的代码似乎在 Docker 容器之外工作。

更新: strace 转储:

stat("/tmp", {st_mode=S_IFDIR|S_ISVTX|0777, st_size=4096, ...}) = 0
gettimeofday({1385247432, 199732}, NULL) = 0
getpid()                                = 127
open("/tmp/tmpf9l14HD", O_RDWR|O_CREAT|O_EXCL, 0600) = 3
unlink("/tmp/tmpf9l14HD")               = 0
fcntl(3, F_GETFL)                       = 0x8002 (flags O_RDWR|O_LARGEFILE)
brk(0)                                  = 0xc94000
brk(0xcb5000)                           = 0xcb5000
fstat(3, {st_mode=S_IFREG|0600, st_size=0, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f7afb9d0000
lseek(3, 0, SEEK_CUR)                   = 0
lstat("/proc/self/fd/3", {st_mode=S_IFLNK|0700, st_size=64, ...}) = 0
munmap(0x7f7afb9d0000, 4096)            = 0
open("/proc/self/fd/3", O_RDWR)         = -1 ESTALE (Stale NFS file handle)

最佳答案

来自C99标准:

The freopen function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used just as in the fopen function.

If filename is a null pointer, the freopen function attempts to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.

所以,编写这段代码的人可能打算将临时文件打开模式从 w+b 更改为 r+ (这主要归结为将流更改为文本模式)。不幸的是,在您的实现中似乎无法以这种方式更改临时文件的打开模式。

我认为这可能是因为关闭临时文件也会删除它,但也可能是 freopenglibc 实现不支持模式freopen 中的更改(手册页甚至没有提到将 NULL 作为第一个参数传递的可能性)。

关于c - 为什么我不能 "freopen"和 "tmpfile"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20168275/

相关文章:

c - printf 中系统调用的输出表现异常

c - kernel.h中min宏中 "(void) (&_min1 == &_min2)"的作用是什么?

docker - 在不同的客户端设备上使用相同的 Docker 机器

Docker 和网络核心应用程序不起作用

java - 使用 JConsole 监控 docker 中的 java 应用程序

mysql - select count(*) from <table> 在 C 中使用 MySQL 函数给出错误结果

python - 如何在 Python 中写入临时文件并再次从中读取?

Python 在尝试执行临时文件时给出 "OSError: Text file busy"

android - 捕获滑动以关闭事件

c - 为什么这个指针操作会失败?