如何打开一个“空"文件? [英] How to open a "nul" file?

查看:45
本文介绍了如何打开一个“空"文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个将标准错误流重定向到某个文件的新进程.创建子进程的代码没有可用的控制台,因此在某些情况下 GetStdHandle(any) 将返回 0.出于某种原因,子进程将尝试复制其所有标准 IO 句柄(子进程的源代码不可用)) 所以它的所有句柄都应该是有效的.

I need to create a new process with redirected standard error stream to some file. The code from which child process is being created has no console available, so there are cases when GetStdHandle(any) will return 0. Child process will try to duplicate all of its standard IO handles for some reason (source code for child process is unavailable) so all of it's handles should be valid.

所以我需要以与可以从控制台运行相同的方式运行该进程:

So I need to run that process in the same manner as it's can be ran from the console with:

someproc <nul >nul 2>err

我看到了一些方法:1. 创建两对管道.这可能是一个很好的解决方案,但对我来说太复杂了.2. 使用 CreateFile("nul", ...) 函数调用打开 "nul" 文件.此调用未创建任何文件,但这对我来说看起来也很奇怪.3. 使用 INVALID_HANDLE_VALUE.这也有效,但我认为另一个子进程可能会出现不同的问题.

I see some ways for this: 1. Create two pair of pipes. This is possibly good solution, but it will be too complex for me. 2. Open "nul" file with CreateFile("nul", ...) function call. No file is being created by this call, but this looks weird too me. 3. Use INVALID_HANDLE_VALUE. This works too, but I think there can be different problems with another child processes.

我相信有更好的方法.

推荐答案

正如最初所说,您已经回答了自己的问题.要打开nul"文件,您只需在调用 CreateFile 时指定 "nul".它看起来很奇怪,因为几乎没有人使用过这个文件名.(我认为它的使用频率不像我看到的 /dev/null 那样频繁.)不过,它完全有效.

As originally phrased, you have already answered your own question. To open a "nul" file, you simply specify "nul" when you call CreateFile. It only looks weird because hardly anyone ever uses that file name. (I don't see it used nearly as often as I see /dev/null.) It's perfectly valid, though.

但如果您发现 Invalid_Handle_Value 也有效,那么请继续使用它.这当然是最简单的.一开始我没想到它会起作用,因为我不希望它可以复制.

But if you've found that Invalid_Handle_Value works, too, then go ahead and use that instead. It's certainly easiest. I wouldn't have expected it to work, initially, since I wouldn't expect it to be duplicable.

这篇关于如何打开一个“空"文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆