UNIX 中的/dev/tty 是什么?

UNIX 中的/dev/tty 是什么?

问题描述:

stdin 和 stdout 文件描述符都指向它.它是如何工作的?有人可以指出一个很好的资源来理解 UNIX 终端和与之交互的系统调用.

Both stdin and stdout file descriptors point to it. How does it work? Can some one point to a good resource for understanding UNIX terminals and system calls that interact with it.

dev/tty 是表示当前控制台的文件系统对象.从命令行将文件复制到此目录"中会将这些文件的内容打印到您的控制台:

dev/tty is a file system object that represents the current console. Copying files into this "directory" from the command line prints out the content of these files to your console:

cp myfile.txt /dev/tty

相当于

cat myfile.txt

这些对象可让您使用熟悉的文件 API 与控制台进行交互.这是将控制台 API 与文件 API 统一的巧妙方法.您可以使用 fopenfprintf 等来与控制台进行交互,就像与常规文件交互一样.

These objects are there to let you use the familiar file APIs to interact with console. It is a clever way to unify console API with file API. You can use fopen, fprintf, etc. to interact with the console in the same way that you interact with regular files.

此示例将 "Hello, world\n" 写入终端:

This example writes "Hello, world\n" to the terminal:

#include <stdio.h>

int main (int argc, const char * argv[]) {
    FILE *f = fopen("/dev/tty", "w");
    fprintf(f, "Hello, world!\n");
    return 0;
}