开发者

How to run a linux app in background process?

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

Like for开发者_JAVA百科 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜