C/C++进程如何知道它是否在后台运行?

ced*_*rou 4 c c++ linux background

我的进程中有一个方法,只有当进程不在后台时才应该运行.如何动态测试当前进程是否在后台?谢谢

sho*_*nex 5

这是我使用的,对于从具有作业控制的shell启动的程序(大多数shell,见下文):

/* 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;
}
Run Code Online (Sandbox Code Playgroud)

如果会话具有控制终端,则前台中只能有进程组,而tcget/setpgrp用于设置此进程组ID.因此,如果您的进程组Id不是前台进程组的进程组ID,那么您不在前台.

如果shell有作业控制,它就可以工作,正如mouviciel指出的链接所说的那样.但是,情况并非总是如此.例如,在使用busybox的嵌入式系统上,可以使用或不使用作业控制来配置shell.