以编程方式检查进程是否在后台运行 [英] Programmatically check if a process is being run in the background

查看:117
本文介绍了以编程方式检查进程是否在后台运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2个问题:

1)是否有任何Linux/Posix API可以知道某个进程是否已作为后台进程被调用?

1) Is there any Linux/Posix API to know if a process has been invoked as a background process?

linux> myprogram &

myprogram的代码是否可以检测到它已被调用以在后台运行(通过&)?

Can the code for myprogram detect that it has been invoked to run in the background (via &) ?

2)是否有任何Linux/Posix API使进程在后台运行,即使该进程已作为前台进程启动? IE.在运行时以某种方式与外壳分离".(要么完全与外壳分离,要么作为外壳的后台进程运行.)

2) Is there any Linux/Posix API to make a process run in the background even if it has been started as a foreground process? I.E. somehow 'detach' from the shell at runtime.. (either detach itself from the shell completely, or run as a background process of the shell).

linux> myprogram
**** starting myprogram as a background job ****
linux>

由于myprogram已从shell分离并在后台运行,因此shell提示应该立即出现.

The shell prompt should come right back to me since myprogram has detached from the shell and is running in the background

推荐答案

1)有两种方法可以知道某个进程是否在后台

1) there are two ways to know whether a process in background

  1. 具有用于SIGTTIN /SIGTTOUT的信号处理程序,并根据哪个信号处理程序(stdin/stdout)进行无阻塞读取/写入.

  1. have a signal handler for SIGTTIN /SIGTTOUT and do a non-blocking read/write depending on which signal handler(stdin/stdout).

检查过程组并将其与终端的getpgrp() == tcgetpgrp(STDOUT_FILENO)

check the process-group and match it with the terminals' getpgrp() == tcgetpgrp(STDOUT_FILENO)

您将需要重复检查,因为该过程可以随时成为前台或后台.

you will need to repeat the check, as the process can be foregrounded or backgrounded anytime.

2)有一个daemon函数可将进程置于后台.建议在进行守护程序时将应用程序的打印重定向到syslog或其他文件.

2) There is a daemon function to put the process in background. its advisable to redirect the application prints to syslog or some other file while daemonizing.

if (daemonize) {
//redirect all prints to syslog or some other logfile
    daemon(0, 0);
}

其中daemonize可能是应用程序是否进入后台的争论.

where daemonize can be an arguement to the application whether to go into background or not.

这篇关于以编程方式检查进程是否在后台运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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