Skip to content

File: low-level APIs for opening null device #122803

@adamsitnik

Description

@adamsitnik

Background and motivation

As of today, BCL does not provie any API for discarding standard input, output, or error of the started process in optimal way. Because of that, users often read the STD OUT/ERR just to ignore it, which is very inefficient. Sample from our code base:

process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;

// Send the output and error streams to empty handlers because the text is also written to the log files
process.OutputDataReceived += (sender, e) => { };
process.ErrorDataReceived += (sender, e) => { };

process.Start();

process.BeginOutputReadLine();
process.BeginErrorReadLine();

This could be avoided if we give the users the ability to open handles to the null device (NUL on Windows, /dev/null on Unix). Those handles can then be passed to the process creation APIs to discard unwanted output or provide empty input.

API Proposal

namespace System.IO;

public static class File
{
+    public static SafeFileHandle OpenNullFileHandle();
     public static SafeFileHandle OpenHandle(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read,
            FileShare share = FileShare.Read, FileOptions options = FileOptions.None, long preallocationSize = 0);

}

API Usage

using SafeFileHandle nullHandle = File.OpenNullFileHandle();

using var procHandle = SafeChildProcessHandle.Start(options, input: nullHandle, output: nullHandle, error: nullHandle);
procHandle.WaitForExit();

Risks

Not in the API design, but the implementations need to enforce CLOEXEC (Unix) / bInheritHandle: false (Windows) semantics on the opened handle to avoid leaking it to child processes unintentionally.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions