【发布时间】:2019-12-05 04:16:12
【问题描述】:
stdin、stdout、stderr 文件描述符默认为 0、1 和 2。但是,当我通过fd = open(foo, 0) 打开一个文件后,我发现fd 现在是 1。1 用于新的文件描述符。现在标准输出文件描述符是什么?或者它已关闭,我需要重新打开它?如果是,如何?有没有办法保留 0、1、2 个文件描述符并从 3 中使用?
/* readslow from the book with my "improve": the unix programming environment */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 512
int main (int argc, char *argv[])
{
char buf[SIZE];
int n, fd;
int t = 10;
if ((argc > 1) && (fd = open(argv[1], 0) == -1)) {error("can't open %s", argv[1]);}
fprintf(stderr, "%d", fd);
for (;;) {
while ((n = read(fd, buf, sizeof buf)) > 0)
write(1, buf, n);
sleep(t);
}
}
fprintf(stderr, "%d", fd)会给我1个。
【问题讨论】:
-
请显示产生该结果的代码。即,请提供minimal reproducible example
-
@kaylum 我用我的代码更新了我的问题。
-
都是我的错。我想念
if ((argc > 1) && (fd = open(argv[1], 0) == -1))中的“)”。真的很难找到这个错误。对不起