【问题标题】:Write to newly opened terminal window写入新打开的终端窗口
【发布时间】: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 &lt;unistd.h&gt;@ 987654332@`#include `
  • 由于你是在linux操作系统下运行的,所以main() always has the return type of int, not void的签名`
  • 只是为了良好的编码习惯,read() 返回一个 ssize_t,而不是 int,并且 write() 的第三个参数是 size_t,而不是 int,如果您使用编译-Wconversion 参数,编译器会告诉你这些问题。应该注意的是,C 的“隐式转换”特性会为您纠正这个问题。

标签: c linux terminal tty


【解决方案1】:

我已在 Linux 中打开控制台并编写了命令 tty。在输出中我有:

/dev/pts/25

这是将所有内容从 foo 文件复制到 bar 和控制台的程序:

…
  if ((con  = open("/dev/pts/2", O_WRONLY)) < 0) {
…

您的程序仅打开一个设备 pts/2,与您所说的控制台 pts/25 不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2016-08-16
    • 2013-10-28
    • 2013-08-12
    • 2014-07-20
    相关资源
    最近更新 更多