[英]how to write a cp function (in linux shell ) in c++ that runs in background?
[英]How can a C/C++ process know if it runs in background?
我的進程中有一個方法,只有當進程不在后台時才應該運行。 如何動態測試當前進程是否在后台? 謝謝
這是我使用的,用於從具有作業控制的外殼啟動的程序(大多數外殼,見下文):
/* 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;
}
如果會話有控制終端,則前台只能有進程組,tcget/setpgrp 用於設置該進程組ID。 因此,如果您的進程組 ID 不是前台進程組的進程組 ID,那么您不在前台。
正如 mouviciel 指向的鏈接所說,如果 shell 具有作業控制,它就可以工作。 然而,情況並非總是如此。 例如,在使用busybox 的嵌入式系統上,shell 可以配置有或沒有作業控制。
嘗試檢查 DISPLAY 的可用性。 那里顯示了xset命令的源代碼如何檢查 Linux 控制台屏幕保護程序是否有黑屏
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.