[英]Does every process have its stdin stdout stderr defined as Keyboard, Terminal etc?
Does every process have stdin
, stdout
and stderr
associated to it to the Keyboard and Terminal? 每个进程都将与stdin
, stdout
和stderr
关联到键盘和终端吗?
I have a small program. 我有一个小程序。 I want to replace the keyboard input to a file called new.txt
. 我想将键盘输入替换为一个名为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
? 现在我的stdio
重定向到FILE
吗?
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. 但是在为您提供命令行窗口输入的操作系统上,从该命令行启动的程序会将stdin连接到键盘,而stdout和stderr都将连接到终端。
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. 当然,具体细节因操作系统而异。
In response to your question: 针对您的问题:
Would this work ? 这行得通吗?
No. dup2()
takes two file descriptors ( int
s) while you're passing it a FILE *
and an int
. 否dup2()
在传递FILE *
和int
会使用两个文件描述符( int
)。 You can't mix file handles ( FILE *
s) and file descriptors ( int
s) like that. 您不能像这样混合使用文件句柄 ( FILE *
s)和文件描述符 ( int
s)。
You could use open
instead of fopen
to open your file as a file descriptor instead of a file handle, or you could use fileno
to get the file descriptor from a file handle. 您可以使用open
而不是fopen
来打开文件作为文件描述符而不是文件句柄,或者可以使用fileno
从文件句柄获取文件描述符。 Or you could use freopen
to reopen the stdin
file handle to a new file. 或者,您可以使用freopen
将stdin
文件句柄重新打开到新文件。
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. 请注意,文件描述符( int
)是POSIX操作系统的一部分,并且只能移植到其他POSIX系统中,而文件句柄( FILE *
s)是C标准的一部分,可以在任何地方移植。 If you use file descriptors, you'll have to rewrite your code to make it work on Windows. 如果使用文件描述符,则必须重写代码才能使其在Windows上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.