Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically check if a process is being run in the background

2 questions:

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

linux> myprogram &

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

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>

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

like image 759
Forhad Ahmed Avatar asked Feb 17 '23 12:02

Forhad Ahmed


2 Answers

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.

like image 185
hiteshradia Avatar answered Apr 27 '23 12:04

hiteshradia


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
like image 34
dutt Avatar answered Apr 27 '23 12:04

dutt