I have a method in my process that should be run only if the process is not in background. How can I dynamically test if the current process is in background ? Thanks
-
3When you say "background" do you mean in the *nix process sense, or in the GUI sense ? – Paul R Oct 15 '10 at 08:23
-
Your phrasing of the title makes no sense to me. C and C++ are programming languages and not properties of unix processes. – Jens Gustedt Oct 15 '10 at 09:02
4 Answers
Here is what I use, for a program launched from a shell with job control (most of the shell, see below):
/* We can read from stdin if :
* - we are in foreground
* - stdin is a pipe end
*/
static int validate_stdin(void) {
pid_t fg = tcgetpgrp(STDIN_FILENO);
int rc = 0;
if(fg == -1) {
debug_printf("Piped\n");
} else if (fg == getpgrp()) {
debug_printf("foreground\n");
} else {
debug_printf("background\n");
rc = -1;
}
return rc;
}
If a session has a controlling terminal, there can be only process group in the foreground, and tcget/setpgrp is used for setting this process group id. So if your process group Id is not the process group Id of the foreground process group, then you are not in foreground.
It works if the shell has job control, as the link pointed by mouviciel says. However, it is not always the case. For example, on embedded system using busybox, the shell can be configured with or without job control.

- 14,975
- 11
- 57
- 91
Check out Unix FAQ: How can a process detect if it's running in the background?
General answer is: You can't tell if you're running in the background.
But you can check if stdin is a terminal: if(isatty(0)) { ... }

- 66,855
- 13
- 106
- 140
-
From your link, general answer is it depends if you have a shell with job control or not. Nowadays, it is quite a standard behaviour. – shodanex Oct 15 '10 at 09:09
-
Since I work for embedded systems, I never take it for granted. But in the common case, you are right. – mouviciel Oct 15 '10 at 09:12
Try to check availability of DISPLAY. There shown source code of xset command How to check if Linux console screensaver has blanked screen
-
-1. What has this to do with running something in the background? The DISPLAY variable is an X thing and has nothing to do with process control. – Noufal Ibrahim Oct 15 '10 at 08:58
This sounds like a bad design. Can you tell us something about this method you're mentioning in your question? As mouviciel said, there's no reliable way.
One suggestion I have is to use the "foreground behaviour" by default and keep the "background behaviour" under a switch like -d
(for daemon mode) or vice versa if your program usually runs in the background. One example of such usage is fetchmail.

- 1
- 1

- 71,383
- 13
- 135
- 169
-
Why the -1? Why do people do this without saying why? It helps to know. – Noufal Ibrahim Oct 15 '10 at 11:34