Programmatically check if a process is being run in the background

前端 未结 4 976
粉色の甜心
粉色の甜心 2021-01-19 16:19

2 questions:

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

linux> myprogram &
4条回答
  •  耶瑟儿~
    2021-01-19 17:07

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

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

    2. 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) 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);
    }
    

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

提交回复
热议问题