Programmatically check if a process is being run in the background

你说的曾经没有我的故事 提交于 2019-12-01 18:30:08

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.

To answer your second part, that's usually called a daemon and they're built something like this.

main()
    pid = fork()
    if pid is child
          run program
    else we are the parent process
       exit to command prompt

A process is in the background if its parent shell process isn't suspended (waiting), which you can check through the PID.

To put a process in the background (detach it completely from the shell at runtime), you use the daemon(3) function.

You might want to read the tty(4) man page. From what I understand, a process in the background does not have any /dev/tty (so open-ing that file would fail).

The TIOCNOTTY ioctl should detach the calling process from its controlling terminal.

You might be interested by the isatty(3) function (e.g. to detect that your stdin or stdout is or not a terminal).

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