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);
当程序的输出被重定向时, isatty 函数会检测到并输出错误信息。例如:
$ ./menu2 > file
You are not a terminal!
也可以将错误流定向到不同的文件,或者将两个输出流合并到一个文件:
$ ./menu2 >file 2>file.error
$ ./menu2 >file 2>&1
2. 使用 /dev/tty 与终端交互
为了防止程序与用户交
超级会员免费看
订阅专栏 解锁全文

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



