Programming C: Find out name of a terminal

Recently I was writing a small experimental program under GNU/Linux. My tiny application needed input from terminal.

ADVERTISEMENTS

I need to find out name of a terminal. Further, I need to know if a particular file descriptor is a tty device or not.

I found ttyname() function which accepts an open file descriptor as its input argument and returns a pointer to the null-terminated pathname of the terminal device.

But how did I know if descriptor refer to a terminal is tty? Simply use C function isatty(desc) which returns 1 if desc is an open descriptor connected to a terminal and 0 else.

Desc can be any one of the following:

  • 0 : Standard input (like keyboard)
  • 1 : Standard output (like screen)
  • 2 : Standard error (like screen)

Under normal circumstances every Linux program has three streams opened for it when it starts up, one for input, one for output, and one for printing diagnostic or error messages. These are typically attached to the user’s terminal but might instead refer to files or other devices, depending on what the parent process chose to set up.

On program startup, the integer file descriptors associated with the streams stdin, stdout, and stderr are 0, 1, and 2, respectively.

Here is sample C guesstty.c program listing:

#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(t));

 return EXIT_SUCCESS;
}

The above code can tell when the standard input is redirected to take data from a file or when the data is coming from terminal.

Compile and run program:
[code]$ make guesstty.c[/code] OR
[code]$ cc guesstty.c -o guesstty [/code] Sample run:
[code]$ ./guesstty 0[/code]Output:

fd is 0, which is a tty

tty name is /dev/pts/1
[code]$ ./guesstty 0 fd is 0, which isn’t a tty

References:

  • ttyname(3)
  • isatty(3)
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source & DevOps topics via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
0 comments… add one

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.