【发布时间】:2015-12-21 11:55:45
【问题描述】:
由于 Linux 中的一切都是文件,我想打印到终端窗口中打开的控制台。
我已在 Linux 中打开控制台并编写了命令 tty。在输出中我有:
/dev/pts/25
这是将所有内容从foo 文件复制到bar 和控制台的程序:
/* Trivial file copy program using low-level I/O */
#include <fcntl.h>
#include <stdlib.h>
#define BSIZE 16384
void main()
{
int fin, fout,con; /* Input and output handles */
char buf[BSIZE];
int count;
if ((con = open("/dev/pts/2", O_WRONLY)) < 0) {
perror("open con ");
exit(1);
}
if ((fin = open("foo", O_RDONLY)) < 0) {
perror("foo");
exit(1);
}
if ((fout = open("bar", O_WRONLY | O_CREAT, 0644)) < 0) {
perror("bar");
exit(2);
}
while ((count = read(fin, buf, BSIZE)) > 0)
{
write(fout, buf, count);
write(con, buf, count);
}
close(fin);
close(fout);
close(con);
}
不幸的是,在bar 包含所需信息时,控制台窗口中没有写入任何内容。如何写入控制台终端窗口?
【问题讨论】:
-
它有效。尝试 strace 程序:在系统调用上检查 -1。可能你把 /dev/pts/25 和 /dev/pts/2 拼错了吗?
-
一个疯狂的猜测:您的 pts 被配置为原始设备。启用熟模式(或至少
echo),您将看到字符。 -
使用ubuntu linux 14.04和gcc,发布的代码编译失败,因为它没有包含
write()和read()和read()和open()的正确头文件建议添加:#include <unistd.h>@ 987654332@`#include` -
由于你是在linux操作系统下运行的,所以
main() always has the return type ofint, notvoid的签名` -
只是为了良好的编码习惯,read() 返回一个
ssize_t,而不是int,并且 write() 的第三个参数是size_t,而不是int,如果您使用编译-Wconversion参数,编译器会告诉你这些问题。应该注意的是,C 的“隐式转换”特性会为您纠正这个问题。