每个进程是否都有其 stdin stdout stderr 定义为键盘、终端等?

发布于 2024-10-21 21:46:33 字数 317 浏览 1 评论 0原文

每个进程是否都有与键盘和终端关联的 stdinstdoutstderr

我有一个小程序。我想将键盘输入替换为名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月依秋水 2024-10-28 21:46:33

不,不是每个进程。但在为您提供命令行窗口进行输入的操作系统上,从该命令行启动的程序会将 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.

短暂陪伴 2024-10-28 21:46:33

回答你的问题:

这行得通吗?

不会。当您向它传递一个 FILE * 和一个 int< 时,dup2() 需要两个文件描述符 (int)。 /代码>。您不能像这样混合文件句柄FILE *)和文件描述符int)。

您可以使用 open 而不是 fopen 将文件作为文件描述符而不是文件句柄打开,或者您可以使用 fileno 来获取来自文件句柄的文件描述符。或者您可以使用 freopen 重新打开新文件的 stdin 文件句柄。

请注意,文件描述符(int)是 POSIX 操作系统的一部分,只能移植到其他 POSIX 系统,而文件句柄(FILE *)是 C 语言的一部分。标准且可随身携带。如果您使用文件描述符,则必须重写代码才能使其在 Windows 上运行。

In response to your question:

Would this work ?

No. dup2() takes two file descriptors (ints) while you're passing it a FILE * and an int. You can't mix file handles (FILE *s) and file descriptors (ints) like that.

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. Or you could use freopen to reopen the stdin file handle to a new file.

Note that file descriptors (ints) 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文