简体   繁体   English

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

[英]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谢谢

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.如果会话有控制终端,则前台只能有进程组,tcget/setpgrp 用于设置该进程组ID。 So if your process group Id is not the process group Id of the foreground process group, then you are not in foreground.因此,如果您的进程组 ID 不是前台进程组的进程组 ID,那么您不在前台。

It works if the shell has job control, as the link pointed by mouviciel says.正如 mouviciel 指向的链接所说,如果 shell 具有作业控制,它就可以工作。 However, it is not always the case.然而,情况并非总是如此。 For example, on embedded system using busybox, the shell can be configured with or without job control.例如,在使用busybox 的嵌入式系统上,shell 可以配置有或没有作业控制。

Check out Unix FAQ: How can a process detect if it's running in the background?查看 Unix 常见问题解答:进程如何检测它是否在后台运行?

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)) { ... }但是您可以检查 stdin 是否为终端: if(isatty(0)) { ... }

Try to check availability of DISPLAY.尝试检查 DISPLAY 的可用性。 There shown source code of xset command How to check if Linux console screensaver has blanked screen那里显示了xset命令的源代码如何检查 Linux 控制台屏幕保护程序是否有黑屏

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.正如mouviciel所说,没有可靠的方法。

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.我的一个建议是默认使用“前台行为”,并将“后台行为”保留在-d (用于守护程序模式)之类的开关下,反之亦然,如果您的程序通常在后台运行。 One example of such usage is fetchmail .这种用法的一个例子是fetchmail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM