我正在学习如何在Linux OS平台上编程,以及如何在后台进程中运行我的应用程序。
例如,在这个场景中:当在shell中执行我的应用程序时,它将自动在后台进程中运行。请注意,当我运行我的应用程序时,我不需要shell中的"&“。执行此操作的标准Linux函数是什么?
如何终止或终止代码中在后台运行的应用程序?我的意思是我不需要执行kill shell命令来在后台终止我的应用程序?或者,如果应用程序满足某个条件,它将自杀或自行终止。
非常感谢。
发布于 2010-06-04 09:30:27
你想让你的程序守护进程。这通常由fork()和其他一些系统调用来完成。
这里有更多详细信息here
使用kill可以终止后台应用程序。对于守护进程来说,将其进程ID (PID)写入一个众所周知的文件中是一种很好的做法,这样就可以很容易地找到它。
发布于 2010-06-04 09:54:29
虽然您应该了解fork() exec() wait()和kill(),但如果daemon(3)存在,有时使用它会更方便。
注意事项:
POSIX.1-2001
中(不过,可能会有其他名称)
如果可移植性不是一个主要问题,那么它是相当方便的。如果可移植性是一个主要问题,您可以随时编写自己的实现并使用它。
从手册页:
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.发布于 2010-06-04 09:27:53
fork(2)为您提供了一个新的进程。在子代中,您可以运行其中一个exec(3)函数,将其替换为一个新的可执行文件。父进程可以使用wait(2)函数之一来等待子进程终止。kill(2)可用于向另一个进程发送信号。
https://stackoverflow.com/questions/2970937
复制相似问题