Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a process read its own "standard out" stream?

How would a process read its own output stream? I am writing automated tests which start a few application sub-processes (applications) in the same process as the test. Therefore, the standard out is a mix of test output and application output.

I want to read the output stream at runtime and fail the test if I see errors from the application. Is this possible/feasible? If so, how do I do it?

Note: I know I could start the applications as their own separate processes and then read their output streams. That's a lot of work from where I am now.

Also note, this is not a dupe of How to test a function's output (stdout/stderr) in Go unit tests, although that ticket is similar and helpful. The other ticket is about capturing output for a single function call. This ticket is about reading the entire stream, continuously. The correct answer is also a little different - it requires a pipe.

like image 761
thebiggestlebowski Avatar asked Mar 15 '19 05:03

thebiggestlebowski


People also ask

Is the standard output stream?

The standard output stream, on the other hand, is a stream that writes its contents to the display. The standard output stream is a convenient place for an old-fashioned text-based application to display its output. And finally, you use the standard error stream to display error messages to the user.

What is the name of the standard output stream?

In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr).

What is standard output stream in C#?

In computer programming, standard streams are preconnected input and output channels between a computer program and its environment (typically a text terminal) when it begins execution. The three I/O connections are called standard input (stdin), standard output (stdout) and standard error (stderr).

What is the use of standard error stream?

The standard error stream is typically used to print any errors that occur when a program is running. Printing program output and errors to different streams allows the user to pipe them to different locations thereby separating them.


1 Answers

Yes, You may use os.Pipe() then process it yourself:

tmp := os.Stdout
r, w, err := os.Pipe()
if err != nil {
    panic(err)
}
os.Stdout = w

Or divert os.Stdout to a another file or strings.Builder.
Here is the detailed answer:
In Go, how do I capture stdout of a function into a string?

like image 87
wasmup Avatar answered Sep 23 '22 18:09

wasmup