0

In my C program, I want to have different behavior whether my process (POSIX) is running in the background or in the foreground. I don't have access to argc/argv.

I was thinking about something in the likes of:

if (isatty(0)) {
  printf("Foreground\n");
} else {
  printf("Background\n");
}

But this isn't working well for me. I get the following result:

$ ./myprog &
Foreground
  • I don't think there is a portable way of finding that out. Specific operating systems may have means of finding out but they won't be cross platform. Perhaps if you explain why you need to know, somebody can suggest an alternative. – JeremyP May 31 '18 at 09:03
  • 2
    There is a good explanation which works on linux, but I have no idea whether it works on posix standards: https://stackoverflow.com/questions/14894261/programmatically-check-if-a-process-is-being-run-in-the-background – Jose May 31 '18 at 09:30
  • 1
    And how will you handle being switched from foreground to background, or from background to foreground? – Andrew Henle May 31 '18 at 09:35
  • Looks like that linked question may be a duplicate. The `getpgrp() == tcgetpgrp(0)` suggestion from an answer to that question is POSIX.1-2001 conformant. – Candy Gumdrop May 31 '18 at 09:37

1 Answers1

1

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
Ketan Mukadam
  • 789
  • 3
  • 7
  • Thanks, I thought isatty(0) would test if the process's stdin was a tty. As in sometimes you can redirect those in- and outputs. I'll test that solution tomorrow, keep you updated. – LateRefrigerator May 31 '18 at 16:44
  • File descriptor 0 is stdin. It doesn't "mostly" refer to stdin, it is stdin, they're synonyms. Furthermore, stdin isn't always a terminal. – user464502 May 31 '18 at 21:51