linux下的stdin stdout和stderr理解

               

在linux中经常会看到stdin,stdout和stderr,这3个可以称为终端(Terminal)的标准输入(standard input),标准输出( standard out)和标准错误输出(standard error)。

通过man stdin查看手册,可以看到它们都是在stdio.h中定义的。 当linux开始执行程序的时候,程序默认会打开这3个文件流,这样就可以对终端进行输入输出操作。下面用c语言模拟下这3个文件流。

标准输入(standard input)

在c语言中表现为调用scanf函数接受用户输入内容,即从终端设备输入内容。也可以用fscanf指明stdin接收内容。 标准输入的文件标识符为0。

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
 
intmain(void)
{
    charstr[10];
    scanf("%s", str);
    fscanf(stdin, "%s", str);
 
    return0;
}

标准输出(standard out)

在c语言中表现为调用printf函数将内容输出到终端上。使用fprintf也可以把内容输出到终端上。标准输出的文件标识符为1。

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
intmain(void)
{
    printf("%s\n""hello");
    fprintf(stdout, "%s\n""hello");
 
    return0;
}

标准错误输出(standard error)

标准错误和标准输出一样都是输出到终端上, 标准错误输出的文件标识符为2。笔者更倾向于从语义上分析:在程序处理的时候,正常的信息输出作为标准输出,产生错误的输出作为标准错误输出。这样在重定向的时候,就可以将正常的信息和错误的信息重定向到不同的文件。

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
intmain(void)
{
    printf("%s\n""hello");
    fprintf(stderr, "%s\n""error");
 
    return0;
}

上面这个程序分别往终端和stderr输出了信息,编译这个程序生成二进制文件a.out,使用下列命令运行,重定向输出。

./a.out 1>log.txt 2>error.txt

这样就把输出的内容hello保存到了log.txt文件,错误的信息error保存到了error.txt文件。(也就是通过管道重定位)

在c语言里,也可以使用freopen函数重定向输出流。

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
intmain(void)
{
    FILE*out = freopen("out.txt""w", stdout);
    printf("%s\n""hello");
 
    return0;
}

上例代码编译执行后,终端上并没输出内容,而是保存到了out.txt这个文件了。

总结

总的来说,stdin,stdout和stderr还是和终端有密切关系,通常在生产环境时,会将这3个流重定向到其它文件。比如编写守护进程的时候,因为守护进程和终端无关,所以往往会将stdin,stdout和stderr重定向到/dev/null去。


           

猜你喜欢

转载自blog.csdn.net/qq_44884619/article/details/89204124