Posted: . At: 9:01 AM. This was 2 years ago. Post ID: 15846
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.



Sponsored



How to test if a C program on Linux is running from a TTY or not.


This simple C program will test whether it is running from a TTY or not. This is a simple test, but it could be quite useful.

#include <stdio.h>
#include <poll.h>
#include <unistd.h>
 
int main(int argc, char* argv[]){
 
        struct pollfd fds[1] = {{.fd = STDIN_FILENO, .events = POLLIN}};
 
        if (!poll(fds, sizeof(fds) / sizeof(struct pollfd), 0)) {
                printf("Running from a TTY\n");
        } else {
                printf("NO TTY.\n");
        }
    return 0;
}

In this example, it gives a funny message when run from a TTY.

┌──(john㉿DESKTOP-PF01IEE)-[~/Documents]
└─$ ./a.out 
Running from a TTY

But when I run it with nohup, it gives the alternate message.

┌──(john㉿DESKTOP-PF01IEE)-[~/Documents]
└─$ nohup ./a.out hi
nohup: ignoring input and appending output to 'nohup.out'
 
┌──(john㉿DESKTOP-PF01IEE)-[~/Documents]
└─$ cat nohup.out 
NO TTY.

This is a simple detection of the TTY and I am sure someone could find a use for this programming tip. Linux is very versatile when you are experimenting with programming code. There is also a function here: https://pubs.opengroup.org/onlinepubs/9699919799/functions/isatty.html. This can detect if the program is running from a TTY or not.

This code will also contain some hints: https://cgit.freebsd.org/src/plain/usr.bin/pr/pr.c.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.