Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a C/C++ process know if it runs in background?

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

like image 753
cedrou Avatar asked Feb 27 '23 01:02

cedrou


2 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.

like image 62
shodanex Avatar answered Mar 08 '23 05:03

shodanex


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)) { ... }

like image 23
mouviciel Avatar answered Mar 08 '23 04:03

mouviciel