如何在后台进程中运行linux应用程序?

时间:2010-06-04 01:22:59

标签: linux

我正在学习如何在Linux OS平台上编程以及在后台进程中运行我的应用程序的实现是什么。

例如在这种情况下:在shell中执行我的应用程序时,它将自动在后台进程中运行。请注意,我不需要“&”在我运行我的应用程序时在shell中。执行此实现的标准Linux功能是什么?

如何杀死或终止代码中后台运行的应用?我的意思是我不需要执行kill shell命令来在后台终止我的应用程序?或者,如果应用程序满足条件,那么它将自行终止或自行终止。

非常感谢。

3 个答案:

答案 0 :(得分:4)

你想要守护你的程序。这通常由fork()和其他一些系统调用完成。

还有更多详情here

使用kill可以杀死后台应用程序。守护进程在一个众所周知的文件中编写进程ID(PID)是一种很好的做法,因此可以很容易地找到它。

答案 1 :(得分:2)

虽然了解fork() exec() wait()kill(),但有时候使用daemon(3)会更方便它存在。

注意事项:

  • 不在POSIX.1-2001
  • 不存在于所有BSD中(但可能会被命名为其他)

如果可移植性不是主要问题,那么它非常方便。如果可移植性 是一个主要问题,您可以随时编写自己的实现并使用它。

从联系手册:

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.

答案 2 :(得分:1)

fork(2)为您提供了一个新流程。在子项中,您运行exec(3)函数之一以将其替换为新的可执行文件。父级可以使用wait(2)函数之一来等待子级终止。 kill(2)可用于向另一个进程发送信号。