跳转到内容

標準串流

本页使用了标题或全文手工转换
维基百科,自由的百科全书

这是本页的一个历史版本,由Chiefwei留言 | 贡献2009年9月18日 (五) 02:55 (增加或调整字词转换代码)编辑。这可能和当前版本存在着巨大的差异。

Unix類Unix系統中,如同某些程式語言介面一樣,標準串流是當一個電腦程式執行時,在它和它的環境間(典型為終端),事先連接的輸入和輸出頻道。這三個I/O連結稱作“標準輸入”、“標準輸出”和“標準錯誤輸出”。

背景

在Unix之前的作業系統, 程式必須明確指出連結到合適的輸入和輸出資料。 On many of those systems, this could be an intimidating programming challenge created by OS-specific intricacies such as obtaining control environment settings, accessing a local file table, determining the intended data set, and handling the correct case of a card reader, magnetic tape drive, disk drive, line printer, card punch, or interactive terminal.


Unix provided several groundbreaking advances, one of which was to provide abstract devices: it removed the need for a program to know or care what kind of devices it was communicating with. Older operating systems forced upon the programmer a record structure and, frequently non-orthogonal data semantics and device control. Unix eliminated this complexity with the concept of a data stream: an ordered sequence of data bytes which can be read until the end of file. A program may also write bytes as desired and need not (and can't easily) declare how many there will be, or how they will be grouped.

Another Unix breakthrough was to automatically associate input and output by default—the program (and programmer) did absolutely nothing to establish input and output for a typical input-process-output program (unless it chose a different paradigm). In contrast, previous operating systems usually required some—often complex—job control language to establish connections, or the equivalent burden had to be orchestrated by the program.

Since Unix provided standard streams, the Unix C runtime environment was obligated to support it as well. As a result, most C runtime environments (and C's descendants), regardless of the operating system, provide equivalent functionality.

標準輸入 (stdin)

標準輸入是指資料(通常是文件)走向程式。程式要求資料傳輸使用的運算。並非所有程式都要求輸入。如dirls程式(顯示一個目錄中的檔名)運行時不用任何輸入。

除非重導向,輸入預期由 鍵盤取得。

標準輸入的檔案描述子為 0 (零)。POSIX <unistd.h> 定義是 STDIN_FILENO;相對應的 <stdio.h> 變數為 FILE* stdin ;類似地, <iostream> 變數為 std::cin

標準輸出 (stdout)

標準輸入是指程式寫輸出資料的串流。程式要求資料傳輸使用的運算。並非所有程式都要求輸出。如mvren程式在成功完成時是沈默的。

除非重導向,輸入為 終端

標準輸出的檔案描述子為 1 (一)。POSIX <unistd.h> 定義是 STDOUT_FILENO;相對應的 <stdio.h> 變數為 FILE* stdout ;類似地, <iostream> 變數為 std::cout

標準錯誤輸出 (stderr)

Standard error is another output stream typically used by programs to output error messages or diagnostics. It is a stream independent of standard output and can be redirected separately. The usual destination is the text terminal which started the program to provide the best chance of being seen even if standard output is redirected (so not readily observed). For example, output of a program in a pipeline is redirected to input of the next program, but errors from each program still go directly to the text terminal.

It is acceptable—and normal—for standard output and standard error to be directed to the same destination, such as the text terminal. Messages appear in the same order as the program writes them, unless buffering is involved. (For example, a common situation is when the standard error stream is unbuffered but the standard output stream is line-buffered; in this case, text written to standard error later may appear on the terminal earlier, if the standard output stream's buffer is not yet full.)


The file descriptor for standard error is 2; the POSIX <unistd.h> definition is STDERR_FILENO; the corresponding <stdio.h> variable is FILE* stderr. The C++ <iostream> standard header provides two variables associated with this stream: std::cerr and std::clog, the former being unbuffered and the latter using the same buffering mechanism as all other C++ streams.

Most shells allow both standard output and standard error to be redirected to the same file using

 >& filename
 Bourne-style shells allow standard error to be redirected to the same destination that standard output is directed to using
   2>&1


Timeline

1950 年代: Fortran

Fortran has the equivalent of Unix file descriptors: UNIT=5 for stdin, UNIT=6 for stdout and UNIT=0 for stderr.

! FORTRAN 77 example
      PROGRAM MAIN
      READ(UNIT=5,*)NUMBER
      WRITE(UNIT=6,'(F5.3)')' NUMBER IS: ',NUMBER
      END

1960: ALGOL 60

ALGOL 60因沒有標準檔案存取而受批評。

1968: ALGOL 68

ALGOL 68's input and output facilities were collectively referred to as the transput. Koster coordinated the definition of the transput standard. This standard included: stand in, stand out, stand error and stand back.

Example:

# ALGOL 68 example #
main:(
REAL number;
getf(stand in,($g$,number));
printf(($"Number is: "g(6,4)"OR "$,number)); # OR #
putf(stand out,($" Number is: "g(6,4)"!"$,number));
newline(stand out)
)
Input: Output:
3.14159
Number is: +3.142 OR Number is: +3.142!

1970 年代: C 和 Unix

C語言 中,標準輸入、標準輸出和標準錯誤輸出分別連接到已存的 Unix 檔案描述子 0 、1 和 2。

1995: Java

Java中, 標準串流被稱為 System.in(標準輸入)、System.out(標準輸出)和 System.err(標準錯誤輸)。

public static void main(String args[]) {
    try {
        BufferedReader br = 
          new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        double number = Double.parseDouble(s);
        System.out.println("Number is:" + number);
    } catch (Exception e) {
        System.err.println("Error:" + e.getMessage());
    }
}

2000s: .NET

In C# and other .NET languages, the standard streams are referred to by System.Console.In (for stdin), System.Console.Out (for stdout) and System.Console.Error (for stderr). Basic read and write capabilities for the stdin and stdout streams are also accessible directly through the class System.Console (e.g. System.Console.WriteLine() can be used instead of System.Console.Out.WriteLine()).


It should be noted that System.Console.In, System.Console.Out and System.Console.Error are System.IO.TextReader (stdin) and System.IO.TextWriter (stdout, stderr) objects, which only allow access to the underlying standard streams on a text basis. Full binary access to the standard streams must be performed through the System.IO.Stream objects returned by System.Console.OpenStandardInput(), System.Console.OpenStandardOutput() and System.Console.OpenStandardError() respectively.

// C# example
public static int Main(string[] args)
{
    try {
        string s = System.Console.In.ReadLine();
        double number = double.Parse(s);
        System.Console.Out.WriteLine("Number is: {0:F3}", number);
        return 0;

    // If Parse() threw an exception
    } catch (System.ArgumentNullException) { 
        System.Console.Error.WriteLine("No number was entered!");
    } catch (System.FormatException) {
        System.Console.Error.WriteLine("The specified value is not a valid number!");
    } catch (System.OverflowException) {
        System.Console.Error.WriteLine("The specified number is too big!");
    }

    return -1;
}
' Visual Basic .NET example

Public Function Main() As Integer
    Dim number As Double
    Dim s As String

    Try
        s = System.Console.In.ReadLine()
        number = CDbl(s)
        System.Console.Out.WriteLine("Number is: {0:F3}", number)
        Return 0
    Catch e As System.InvalidCastException
        ' if CDbl() threw an exception
        System.Console.Error.WriteLine("No number was entered!")
        Return 1
    End Try
End Function

When applying the System.Diagnostics.Process class one can use the instance properties StandardInput, StandardOutput, and StandardError of that class to access the standard streams of the process.

Console is not same to Dos Command Window.

圖形使用者介面

圖形使用者介面 rarely make use of the standard streams. Consequently, redirecting GUI programs or constructing a GUI pipeline is neither practical nor useful. The nearest analog is probably cutting (or copying) from one application and pasting into another. Since manual user operations are required, moving large numbers of pastes is not especially efficient. One notable exception is the dwm tiling window manager, which displays data directed through stdin on a status bar.

Some GUI programs, primarily on Unix, still write debug information to standard error.
Others may take files to operate from standard in, for example many Unix media players do so.

GTK-server can use stdin as communication interface with an interpreted program to realize a GUI.

另見

參考

外部連結