简体   繁体   English

为什么 termcaps 在 `write` 系统调用之前不起作用?

[英]Why don't termcaps work before a `write` syscall?

Why is the output of this program not getting underlined为什么这个程序的输出没有下划线

int main() {
  tgetent(NULL, getenv("TERM"));
  tputs(tgetstr("us", NULL), 1, &putchar);
  write(1, "Hello world!\n", 13);
  tputs(tgetstr("ue", NULL), 1, &putchar);
}

but this is ?但这

int main() {
  tgetent(NULL, getenv("TERM"));
  tputs(tgetstr("us", NULL), 1, &putchar);
  puts("Hello world!");
  tputs(tgetstr("ue", NULL), 1, &putchar);
}

EDIT编辑

The issue is, indeed, about buffer management!问题确实是关于缓冲区管理! If I add fflush , the string is properly underlined如果我添加fflush ,该字符串将正确加下划线

int main() {
  tgetent(NULL, getenv("TERM"));
  tputs(tgetstr("us", NULL), 1, &putchar);
  fflush(stdout);
  write(1, "Hello world!\n", 13);
  tputs(tgetstr("ue", NULL), 1, &putchar);
}

The reason for the difference is that putchar and puts are buffered , while write is not.不同的原因是putcharputsbuffered ,而write不是。 In this example在这个例子中

int main() {
  tgetent(NULL, getenv("TERM"));
  tputs(tgetstr("us", NULL), 1, &putchar);
  write(1, "Hello world!\n", 13);
  tputs(tgetstr("ue", NULL), 1, &putchar);
}

the characters written by写的字符

write(1, "Hello world!\n", 13);

are likely to get to the screen first, because (unlike the tputs calls) they are written immediately.很可能首先到达屏幕,因为(与tputs调用不同)它们是立即写入的。 The characters written by the tputs calls are stored in a buffer (which generally is much larger than the strings returned from tgetstr ), and since you provided no other way to flush the buffer, those are written by the runtime's cleanup as it exits.通过书面的文字tputs调用存储在缓存(通常比从返回的字符串大得多tgetstr ),因为你没有提供其他的方式来刷新缓冲区,这些都是由运行时的清理,因为它退出写入。

Without an explicit return statement, the C standard guarantees that it has the same effect as calling exit (which does an fflush on each open file—including streams such as stdout ).如果没有显式 return 语句,C 标准保证它具有与调用exit相同的效果(它对每个打开的文件执行fflush包括诸如stdout 之类的流)。

While you could in principle construct a termcap which had extremely long strings, termcap descriptions are supposed to be limited to 1023 bytes (and even terminfo descriptions are generally limited to 4096 bytes), while the standard I/O buffer size is generally several times that limit, so you wouldn't see those tputs calls written out without a lot of work (ie, changing the runtime...).虽然原则上您可以构造一个具有极长字符串的 termcap,但 termcap 描述应该限制为 1023 字节(甚至 terminfo 描述通常限制为 4096 字节),而标准 I/O 缓冲区大小通常是其数倍限制,所以你不会看到那些没有大量工作的tputs调用(即,更改运行时......)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM