=Start=
缘由:
整理学习在进行Linux下C编程中碰到的一些知识点,方便以后进行参考。
正文:
参考解答:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main( int argc, char **argv){ int t, fd; if ( argc == 1 ){ printf( "Syntax: %s 0/1/2\n" , argv[ 0 ]); exit(EXIT_SUCCESS); } fd = atoi(argv[ 1 ]); t = isatty(fd); if ( t ) printf( "fd is %d, which is a tty\n" , fd); else printf( "fd is %d, which isn't a tty\n" , fd); if ( t == 1 ) printf( "tty name is %s\n" , ttyname(fd)); return EXIT_SUCCESS; } /* #include <unistd.h> char *ttyname(int fd); // 执行成功时返回一个合法指针,否则返回 NULL int ttyname_r(int fd, char *buf, size_t buflen); int isatty(int fd); //返回 1 则表明 fd 是一个指向终端的文件描述符;否则返回 0 */ |
&
参考链接:
http://man7.org/linux/man-pages/man3/ttyname.3.html
http://www.iteedu.com/os/linux/linuxprgm/linuxcfunctions/console/ttyname.php
https://www.cyberciti.biz/tips/programming-c-find-out-name-of-a-terminal.html
https://www.kancloud.cn/wizardforcel/linux-c-api-ref/98624
https://stackoverflow.com/questions/36298779/determining-which-tty-a-program-uses/36299446
https://stackoverflow.com/questions/26168998/running-who-am-i-in-a-single-command-with-sudo-doesnt-return-anything
https://stackoverflow.com/questions/25334464/why-does-using-pipes-with-who-cause-mom-not-to-like-me
http://blog.csdn.net/xingzhibo/article/details/38924971
terminal/shell/tty/console之间的区别到底在哪?
https://unix.stackexchange.com/questions/4126/what-is-the-exact-difference-between-a-terminal-a-shell-a-tty-and-a-con
TTY解密
http://www.linusakesson.net/programming/tty/
https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/
=END=
《“Linux下的C语言#isatty和ttyname”》 有 1 条评论
http://man7.org/linux/man-pages/man3/ttyname.3.html#RETURN_VALUE
http://man7.org/tlpi/code/online/dist/tty/ttyname.c.html
http://www.codeforge.com/read/217200/apue.2e-_-termios-_-ttyname.c__html
`
由ttyname()函数返回的指针不要主动free掉,否则会掉进坑里。。。
Return the device name (as a statically-allocated) string if found, or NULL if the device is not found or an error occurs.
从上面的代码中可以看出,ttyname()返回的是一个静态分配的字符串,这对于一个Demo演示程序来说还没什么(反正很快就退出了),但是如果代码是用于在一个长时间运行的进程中实现某种功能的话,这个问题可能会把你给坑惨,我就差点没有爬起来。。。
由此总结出的一点经验:
如果可能的话,尽量使用传参的方式接收结果,尽量避免在函数中malloc然后返回给调用者,因为调用者很可能就会忘了free!!!
`