0

I'm interested in Linux specifically, but an answer for other Unices would be great as well: Does the system have a way of signaling to a process that it's been launched in the background? In other words, is there a signal I can trap or something I can check from within a Bash/Perl/Python script or similar to tell me if the script was backgrounded when it was launched?

Joseph R.
  • 39,549

1 Answers1

2

There are several possible meanings to "background" in this context.

It could mean it doesn't have a controlling terminal. (For example, something started from cron, systemd, or init).

If it has been not just backgrounded, but orphaned from its parent process (getppid), its parent process would be pid 1. This can happen with or without a controlling terminal.

If the process has a controlling terminal, it can be in the foreground or in the background.

If a process is in the foreground, the getpgrp and tcgetpgrp functions will return the same value (assuming tcgetpgrp is given the file descriptor to the controlling terminal -- for example 2=stderr).

If a process is in the background, getpgrp and tcgetpgrp will return different numbers.

If a process is in the foreground and it is stopped, it will receive one of the signals SIGSTOP or SIGTSTP. Note that SIGSTOP can't be caught, and if you catch SIGTSTP it will prevent your job from being stopped.

When your process is resumed from being stoped, you get signal SIGCONT, after which you can check if you are in the foreground or background.

If a process was in the background and are brought to the foreground, I don't think it gets any signal, but the above check would still work.

If a process is in the background and attempts input or (maybe) output, you would get (respectively) SIGTTIN or SIGTTOU which you could catch.

The above is correct for POSIX systems, which covers linux and most unix systems.

Note that if your program is in the middle of a pipe, stdin and stdout will not be the controlling terminal (or one of them won't be if it's at either end of a pipe). Also, stderr can also be redirected (but this is less likely). You could get the controlling terminal by opening /dev/tty (which will fail if there isn't one), but this is unportable. (I'm not sure if there's a better way.)

user10489
  • 6,740