从 C 程序中,如何知道进程是 运行 在前台还是后台?

From a C program, how to know if the process is running in the foreground or background?

在我的 C 程序中,无论我的进程 (POSIX) 运行 在后台还是在前台,我都希望有不同的行为。 我无法访问 argc/argv

我在想类似的事情:

if (isatty(0)) {
  printf("Foreground\n");
} else {
  printf("Background\n");
}

但这对我来说效果不佳。我得到以下结果:

$ ./myprog &
Foreground

isatty()man page明确表示函数test whether a file descriptor refers to a terminal。当您将“0”作为参数传递时,它主要指的是 STDIN,因此 isatty() 将始终 return TRUE,这意味着您的代码行为类似于

if (TRUE) {
  printf("Foreground\n");
} else {
  printf("Background\n");
}

如评论所示,检查前台进程与后台进程的正确方法就像这段代码

#include <unistd.h>
#include <stdio.h>

int main()
{
pid_t console_pid = tcgetpgrp(STDOUT_FILENO);
pid_t my_pid = getpgrp();
if(console_pid == my_pid)
   printf("process foregrounded\n");
else
   printf("process backgrounded\n");
return 0;
}

这是我的 ubuntu 机器上的输出

ubuntu@4w28n62:~$ ./a.out
process foregrounded
ubuntu@4w28n62:~$ ./a.out &
[1] 4814
ubuntu@4w28n62:~$ process backgrounded

[1]+  Done                    ./a.out