The man page of isatty()
clearly indicates that the function test whether a file descriptor refers to a terminal
. When you pass '0' as a argument, it mostly refers to STDIN, so isatty() will always return TRUE, that means you code behaves like
if (TRUE) {
printf("Foreground\n");
} else {
printf("Background\n");
}
As indicated by the comments, the correct way to check foreground vs background process is like this code
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t console_pid = tcgetpgrp(STDOUT_FILENO);
pid_t my_pid = getpgrp();
if(console_pid == my_pid)
printf("process foregrounded\n");
else
printf("process backgrounded\n");
return 0;
}
Here is the output on my ubuntu machine
ubuntu@4w28n62:~$ ./a.out
process foregrounded
ubuntu@4w28n62:~$ ./a.out &
[1] 4814
ubuntu@4w28n62:~$ process backgrounded
[1]+ Done ./a.out