Detecting background operation

微笑、不失礼 提交于 2021-01-27 07:45:55

问题


In C, what is the way to detect a program was called in "background mode" ? I have a program I would like to launch either interactively or in background.

How can I detect I should not be reading from stdin and end in a "Stopped : tty input" state ?

Should I test that stdin is closed ? How can I do that ?

Edit : isatty seems like a good idea, but what happen if stdin is a pipe end, and not a tty ?


回答1:


Use the tcgetpgrp() function on the file descriptor of the controlling terminal (e.g. STDIN_FILENO or 0 for stdin) to check whether the current foreground process group is equal to your own process group (from getpgrp()). However the foreground process group could change at any time, as your program is moved between foreground and background. For example, it could change immediately after you call tcgetpgrp() and before you test it. So keep this in mind if you are going to take any action based on this; it is not a reliable method of avoiding SIGTTIN.

#include <unistd.h>
pid_t fg = tcgetpgrp(STDIN_FILENO);
if (fg == -1) {
    /* stdin is not controlling terminal (e.g. file, pipe, etc.) */
} else if (fg == getpgrp()) {
    /* foreground */
} else {
    /* background */
}



回答2:


1) You should check if stdin is open, and open /dev/null to it if it closed.

2) You can use isatty which "returns 1 if desc is an open file descriptor connected to a terminal and 0 otherwise"



来源:https://stackoverflow.com/questions/1455301/detecting-background-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!