tags:

views:

49

answers:

3

Hi,

I am learning how to program in Linux OS platform and what is the implementation to run my app in background process.

Like for example in this scenario: When executing my app in the shell it will automatically run in background process. Take note that I don't need the "&" in the shell when I run my app. What standard Linux function to do this implementation?

And how can I kill or terminate the app that was run in background in the code? What I mean is I don't need to execute the kill shell command to terminate my app in background? Or if the app meets a condition then it will kill itself or terminate itself.

Many thanks.

+1  A: 

fork(2) gives you a new process. In the child you run one of the exec(3) functions to replace it with a new executable. The parent can use one of the wait(2) functions to wait for the child to terminate. kill(2) can be used to send a signal to another process.

Ignacio Vazquez-Abrams
+4  A: 

You want to daemonize your program. This is generally done by fork() and a few other system calls.

There are more details here

Background applications can be killed by using kill. It is good practice for a daemon to write its process ID (PID) in a well-known file so it can be located easily.

Yann Ramin
What you mean is I have to save the value of the PID of the app in a file so that if I want to terminate the the app I just read that value and use that value to kill the app using the kill shell command inside of the same code file?
sasayins
@sasayins: If you are killing the process from another program (not a script) the `kill(2)` function should be used. If you want to kill your child process by the parent, there is no need for the PID file as `fork` returns the PID to the parent.
Yann Ramin
+2  A: 

While you should learn about fork() exec() wait() and kill(), its sometimes more convenient to just use daemon(3) if it exists.

Caveats:

  • Not in POSIX.1-2001
  • Not present in all BSD's (may be named something else, however)

If portability is not a major concern, it is rather convenient. If portability is a major concern, you can always write your own implementation and use that.

From the manpage:

SYNOPSIS
       #include <unistd.h>

       int daemon(int nochdir, int noclose);

DESCRIPTION
       The daemon() function is for programs wishing to detach themselves from the
       controlling terminal and run in the background as system daemons.

       If nochdir is zero, daemon() changes the calling process's current working directory
       to the root directory ("/"); otherwise, the current working directory is left 
       unchanged.

       If noclose is zero, daemon() redirects standard input, standard output and standard
       error to /dev/null; otherwise, no changes are made to these file descriptors.
Tim Post