c - 获取标准输出 c 的文件描述符
问题描述
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。
解决方案
[撰写此答案时,问题中没有代码。open
我已经接受了 OP 的说法,即由is返回的文件描述符1
,由于放错了括号,结果证明这是不真实的。]
我
fd
现在发现是 1。1 用于新的文件描述符。
发生这种情况的唯一方法是关闭 fd 1。
现在标准输出文件描述符是什么?
fileno(stdout)
将为您fd
提供与句柄相关联的信息。
有没有办法保留 0、1、2 个文件描述符并从 3 中使用?
如果不关闭 fd 0、1 和 2,它们将不会被重用。open
使用编号最小的未使用文件描述符。
如果您想断开 fd 0、1 或 2,请不要关闭它们。这会导致各种问题。重新打开它们/dev/null
。
或者它已关闭,我需要重新打开它?如果是,如何?
您可以使用dup2
使 fd 成为另一个 fd 的别名。
推荐阅读
- android - 如何在 network_security_config.xml 中包含 BuildConfig 或资源
- css - 从 React 中的一个远程组件触发一个组件中的 CSS 动画
- python - Sklearn Bagging SVM 总是返回相同的预测
- c# - 如何通过 Play Services Resolver 删除 pod?
- python - 在 django 中使用 id 作为 url 有什么解决方案吗?
- android - 调试 APK 安装被播放保护阻止
- javascript - 在nodejs中使用rest auth api
- java - 如何在 EclipseLink JPQL 查询中指定模式?
- c - 便利店程序的最终价值是正确的,但是当您输入付款时,它会计算错误
- oracle - Oracle OSB cdata 传递到请求信封