I am reading the source code of coreutils and I came to read tty.c
code.
Main function of tty
is as follows:
int
main (int argc, char **argv)
{
char *tty;
int optc;
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
initialize_exit_failure (TTY_WRITE_ERROR);
atexit (close_stdout);
silent = false;
while ((optc = getopt_long (argc, argv, "s", longopts, NULL)) != -1)
{
switch (optc)
{
case 's':
silent = true;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (TTY_FAILURE);
}
}
if (optind < argc)
error (0, 0, _("extra operand %s"), quote (argv[optind]));
tty = ttyname (STDIN_FILENO);
if (!silent)
{
if (tty)
puts (tty);
else
puts (_("not a tty"));
}
exit (isatty (STDIN_FILENO) ? EXIT_SUCCESS : EXIT_FAILURE);
}
To my understanding the line which gets the current tty is tty = ttyname (STDIN_FILENO);
But when I run tty
using strace
in the output of strace
there is no call to ttyname
.
What is the reason?
Here is the output of strace:
> strace -c tty
/dev/pts/3
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
0.00 0.000000 0 1 read
0.00 0.000000 0 1 write
0.00 0.000000 0 3 open
0.00 0.000000 0 5 close
0.00 0.000000 0 1 stat
0.00 0.000000 0 5 fstat
0.00 0.000000 0 10 mmap
0.00 0.000000 0 4 mprotect
0.00 0.000000 0 2 munmap
0.00 0.000000 0 3 brk
0.00 0.000000 0 2 ioctl
0.00 0.000000 0 1 1 access
0.00 0.000000 0 1 execve
0.00 0.000000 0 1 readlink
0.00 0.000000 0 1 arch_prctl
------ ----------- ----------- --------- --------- ----------------
100.00 0.000000 41 1 total
No ttyname
is the list!
Best Answer
The reason is that
ttyname(3)
isn't a system call, it's a C library function. You can check out its implementation, e.g. inglibc
, to see what system calls it uses itself (and which you'll then see instrace
's output).To trace library calls on Linux, you can use ltrace (which can also trace system calls). (Thanks to Marki555 for the suggestion.)