isatty() — Test if descriptor represents a terminal
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1 |
both |
Format
#define _POSIX_SOURCE
#include <unistd.h>
int isatty(int fildes);
General description
Determines if a file descriptor, fildes, is associated with a terminal.
isatty() only works in an environment where either a controlling terminal exists, or stdin and stderr refer to tty devices. Specifically, it does not work in a TSO environment.
Returned value
isatty() returns 1 if the given file descriptor is a terminal, or 0 otherwise.
Special behavior for XPG4
isatty()
returns 1 if the given file descriptor is a terminal, or 0 otherwise
and sets errno to one of the following values:
- Error Code
- Description
- EBADF
- The fildes argument is not a valid open file descriptor.
- ENOTTY
- The fildes argument is not associated with a terminal.
Example
CELEBI03
/* CELEBI03
This example determines if a file descriptor is
associated with a terminal.
*/
#define _POSIX_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void check_fd(int fd) {
printf("fd %d is ", fd);
if (!isatty(fd))
printf("NOT ");
puts("a tty");
}
main() {
int p[2], fd;
char fn[]="temp.file";
if (pipe(p) != 0)
perror("pipe() error");
else {
if ((fd = creat(fn, S_IWUSR)) < 0)
perror("creat() error");
else {
check_fd(0);
check_fd(fileno(stderr));
check_fd(p[1]);
check_fd(fd);
close(fd);
unlink(fn);
}
close(p[0]);
close(p[1]);
}
}
Output
fd 0 is a tty
fd 2 is a tty
fd 4 is NOT a tty
fd 5 is NOT a tty