【问题标题】:File Descriptors, open() returns zero文件描述符,open() 返回零
【发布时间】:2012-11-01 01:15:22
【问题描述】:

我打开一个文件并想在其中写一些东西。问题是 fd2 出于某种原因是 0。它没有写入文件,而是写入终端。我没有在我的代码中的任何地方关闭(0)。为什么我得到 fd = 0 而不是例如 3。在终端上写的原因是 fd 的值为零?我知道 fd = 0 是标准输入,

有什么想法吗?谢谢你。

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
    DieWithError("open() failed");

printf("FD2 = %d",fd2);     //returns me zero

bzero(tempStr, sizeof(tempStr));
bzero(hostname, sizeof(hostname));

gethostname(hostname, sizeof(hostname));

sprintf(tempStr, "\n%sStarting FTP Server on host %s in port %d\n", ctime(&currentime), hostname, port);

if (write(fd2, tempStr, strlen(tempStr)) == -1)
    DieWithError("write(): failed");

【问题讨论】:

  • 什么是logfile?是/dev/console吗?
  • 如果您使用的是 Linux,请通过 strace 运行它。
  • logFile 只是 logFile.log 的路径
  • 如果你不能可靠地得到你的括号正确(你不能 - 你的另一个问题,System call open() permissions,也充满了放错位置的括号),然后分开:fd2 = open(logFile, O_RDWR | O_APPEND | O_CREAT, 0666); if (fd2 == -1) { ... }。您出错的可能性要小得多。
  • 至于为什么日志输出会出现在你的终端上,正常的设置方式是标准输入、标准输出和标准错误往往都是到你的终端的读/写连接,所以你可以写入标准输入并从标准输出和标准错误中读取(我有一份按我的意图打字的工作)。因此,您错误的括号表达式以您写入标准输入结束,当它是终端时通常是可写的。

标签: c


【解决方案1】:

您的条件已关闭。注意括号。应该是:

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
//                                                        ^^^    ^^^

有时最好不要比自己聪明:

int fd = open(...);

if (fd == -1) { DieWithError(); }

【讨论】:

    【解决方案2】:

    这是错误的。

    if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
    

    你想要这个。

    if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
    

    很难看,因为这行太长了,但是括号放错了地方。总之,

    if ((   fd2 = open(...) == -1     )) // your code
    if ((   fd2 = (open(...) == -1)   )) // equivalent code
    if ((   (fd2 = open(...)) == -1)  )) // correct code
    

    如果线路太长,最好不要放在if...

    #include <err.h>
    
    fd2 = open(...);
    if (fd2 < 0)
        err(1, "open failed");
    

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 2023-04-07
      • 2021-06-24
      • 1970-01-01
      • 2019-05-22
      • 2019-06-11
      • 2015-07-25
      相关资源
      最近更新 更多