每个进程是否都有其 stdin stdout stderr 定义为键盘、终端等?
每个进程是否都有与键盘和终端关联的 stdin
、stdout
和 stderr
?
我有一个小程序。我想将键盘输入替换为名为 new.txt
的文件。我该怎么办?
FILE *file1
fopen("new.txt", "r")
close(0); // close the stdio
dup2(file1, 0);
这行得通吗?现在我的 stdio
被重定向到 FILE
?
Does every process have stdin
, stdout
and stderr
associated to it to the Keyboard and Terminal?
I have a small program. I want to replace the keyboard input to a file called new.txt
. How do I go about it?
FILE *file1
fopen("new.txt", "r")
close(0); // close the stdio
dup2(file1, 0);
Would this work? Now my stdio
is redirected to the FILE
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不是每个进程。但在为您提供命令行窗口进行输入的操作系统上,从该命令行启动的程序会将 stdin 连接到键盘,并将 stdout 和 stderr 都连接到终端。
如果一个程序启动另一个程序,那么第二个程序的标准流通常会以某种方式连接到第一个程序;例如,第一个程序可能有一个开放描述符,通过它可以发送文本并假装它是第二个进程的“键盘”。当然,详细信息因操作系统而异。
No, not every process. But on operating systems that give you a command-line window to type in, a program started from that command line will have stdin connected to the keyboard, and stdout and stderr both going to the terminal.
If one program starts another, then often the second program's standard streams are connected to the first program in some way; for example, the first program may have an open descriptor through which it can send text and pretend that it's the "keyboard" for the second process. The details vary by operating system, of course.
回答你的问题:
不会。当您向它传递一个
FILE *
和一个int< 时,
dup2()
需要两个文件描述符 (int
)。 /代码>。您不能像这样混合文件句柄(FILE *
)和文件描述符(int
)。您可以使用
open
而不是fopen
将文件作为文件描述符而不是文件句柄打开,或者您可以使用fileno
来获取来自文件句柄的文件描述符。或者您可以使用 freopen 重新打开新文件的 stdin 文件句柄。请注意,文件描述符(
int
)是 POSIX 操作系统的一部分,只能移植到其他 POSIX 系统,而文件句柄(FILE *
)是 C 语言的一部分。标准且可随身携带。如果您使用文件描述符,则必须重写代码才能使其在 Windows 上运行。In response to your question:
No.
dup2()
takes two file descriptors (int
s) while you're passing it aFILE *
and anint
. You can't mix file handles (FILE *
s) and file descriptors (int
s) like that.You could use
open
instead offopen
to open your file as a file descriptor instead of a file handle, or you could usefileno
to get the file descriptor from a file handle. Or you could usefreopen
to reopen thestdin
file handle to a new file.Note that file descriptors (
int
s) are part of POSIX operating systems and are only portable to other POSIX systems, while file handles (FILE *
s) are part of the C standard and are portable everywhere. If you use file descriptors, you'll have to rewrite your code to make it work on Windows.