检测后台操作 [英] Detecting background operation

查看:51
本文介绍了检测后台操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,以后台模式"调用检测程序的方法是什么?我有一个程序想以交互方式或在后台启动.

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.

如何检测到我不应该从stdin读取并以"Stopped:tty输入"状态结束?

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

我应该测试stdin已关闭吗?我该怎么办?

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

isatty似乎是个好主意,但是如果stdin是管道末端而不是tty会发生什么?

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

推荐答案

使用 tcgetpgrp() 函数在控制终端的文件描述符上(例如, STDIN_FILENO 或stdin为0),以检查当前前台进程组是否等于您自己的进程组(来自 getpgrp() ).但是,随着您的程序在前台和后台之间移动,前台进程组可以随时更改.例如,在您调用 tcgetpgrp()之后并在测试之前,它可能会立即更改.因此,如果您要基于此采取任何措施,请记住这一点;这是避免 SIGTTIN 的可靠方法.

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 */
}

这篇关于检测后台操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆