Linux 终端编程深入解析
1. 终端输出重定向检测
在 Linux 编程中,有时需要确保程序在终端环境下运行。可以使用 isatty 函数来检测标准输出是否连接到终端。以下是示例代码:
if(!isatty(fileno(stdout))) {
fprintf(stderr,"You are not a terminal!\n");
exit(1);
}
do {
choice = getchoice("Please select an action", menu);
printf("You have chosen: %c\n", choice);
} while(choice != 'q');
exit(0);
当执行 ./menu2 > file 时,程序会输出 You are not a terminal! ,因为标准输出已被重定向到文件。
2. 直接与终端交互
若要防止程序与用户交互的部分被重定向,可直接读写 /dev/tty 设备。以下是 menu3.c 的示例代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
char *menu[] = {
"a - add new record
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



