c - 为什么 stdout 在 gnu coreutils 中不等于 1?

标签 c stdout libc gnu-coreutils

测试平台为 32 位 x64 Linux,coreutils 8.5。

base64的源码中,fwrite会使用stdout 输出base64编码的字符串

  1. 当我使用 ltrace 打印所有 libc 调用时,我们可以看到 stdout 等于 0xb772da20

    __libc_start_main(0x8048eb0, 2, 0xbf892f74, 0x804cb50, 0x804cbc0 <unfinished ...>
    
    strrchr("base64", '/')                                                         = NULL
    setlocale(6, "")                                                               = "en_US.UTF-8"
    bindtextdomain("coreutils", "/usr/share/locale")                               =      "/usr/share/locale"
    textdomain("coreutils")                                                        = "coreutils"
    __cxa_atexit(0x804a3b0, 0, 0, 0xbf892f74, 2)                                   = 0
    getopt_long(2, 0xbf892f74, "diw:", 0x0804d1a0, NULL)                           = -1
    fopen64("testbase64", "rb")                                                    = 0x8591878
    fileno(0x8591878)                                                              = 3
    posix_fadvise64(3, 0, 0, 0, 0)                                                 = 0
    fread_unlocked(0xbf89225c, 1, 3072, 0x8591878)                                 = 900
    fwrite_unlocked("Ly8gcXVpY2tTb3J0LmMKI2luY2x1ZGUg"..., 1, 76, 0xb772da20)      = 76
    
  2. 当我这样修改base64的代码时:

    int main (int argc, char **argv)
    {
    
      printf("%p \n", stdout);
      int opt;
      FILE *input_fh;
      const char *infile;
      .....
    

输出仍然是 0xb772da20 ,这对我来说很奇怪,因为这是 base64.c 的第一行。

我在coreutils的lib文件夹下grep

grep stdout *.h

而且我没有看到任何标准输出的预定义。

谁能帮我解释为什么 stdout 会被定义为“0xb772da20”,而不是 1,而不是 0?

最佳答案

根据 stdout(3) , stdout 是一个指针(指向某些 FILE 不透明结构),因为它是一个文件流。它不是文件描述符。它的文件描述符是 STDOUT_FILENO 确实是 1。

在我的 Gnu libc Linux 系统上,我在 /usr/include/stdio.h 的第 169 行附近:

/* Standard streams.  */
extern struct _IO_FILE *stdin;      /* Standard input stream.  */
extern struct _IO_FILE *stdout;     /* Standard output stream.  */
extern struct _IO_FILE *stderr;     /* Standard error output stream.  */
/* C89/C99 say they're macros.  Make them happy.  */
#define stdin stdin
#define stdout stdout
#define stderr stderr

在那之前(第48行)有

typedef struct _IO_FILE FILE;

另见 this answer一个相关的问题。

关于c - 为什么 stdout 在 gnu coreutils 中不等于 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21585388/

相关文章:

Android libc版本和malloc实现

c - 调用 clock_gettime() 时,返回的 tv_nsec 字段实际上可能超过一秒吗?

c++ - SSE/AVX 寄存器的非零字节索引

c - Break 语句的行为

c - 在 C 中将文件发送到标准输出

python - 为什么加载libc共享库有 "' LibraryLoader' object is not callable”错误?

c - 通过指针传递矩阵时出现缺陷值

c - printf 与 int C 组合时输出为 null

node.js - 将 process.stdout 设置为每个 Node.js 核心集群工作线程的文件

unit-testing - 如何在 Jenkins 中保持单元测试输出