编写Unix守护进程 [英] Writing a unix daemon

查看:64
本文介绍了编写Unix守护进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Unix中编写守护程序。我了解该部分如何使守护程序启动并运行。现在,我希望守护程序在将命令定向到守护程序时在shell中键入命令时进行响应。

I'm trying to code a daemon in Unix. I understand the part how to make a daemon up and running . Now I want the daemon to respond when I type commands in the shell if they are targeted to the daemon.

例如:

让我们假设守护程序名称为 mydaemon

Let us assume the daemon name is "mydaemon"

在终端1中,键入mydaemon xxx。
在终端2中,键入mydaemon yyy。

In terminal 1 I type mydaemon xxx. In terminal 2 I type mydaemon yyy.

mydaemon应该能够接收参数 xxx和 yyy。

"mydaemon" should be able to receive the argument "xxx" and "yyy".

推荐答案

如果我正确地解释了您的问题,那么您必须将其作为应用程序级结构来进行。也就是说,这是特定于您的程序的事情,您将需要自己编写代码。

If I interpret your question correctly, then you have to do this as an application-level construct. That is, this is something specific to your program you're going to have to code up yourself.

我采用的方法是编写带有这个想法的 mydaemon它是包装器:它检查进程表或pid文件,以查看 mydaemon是否已在运行。如果不是,则派生/执行您的新守护程序。如果是这样,则将参数发送给它。

The approach I would take is to write "mydaemon" with the idea of it being a wrapper: it checks the process table or a pid file to see if a "mydaemon" is already running. If not, then fork/exec your new daemon. If so, then send the arguments to it.

对于将参数发送给它,我将使用命名管道,如下所述:什么是命名管道?本质上,您可以将命名管道视为类似于 stdin,但它们看起来像是标准输入。文件保存到系统的其余部分,因此您可以在运行的 mydaemon中打开它们并检查其输入。

For "send the arguments to it", I would use named pipes, like are explained here: What are named pipes? Essentially, you can think of named pipes as being like "stdin", except they appear as a file to the rest of the system, so you can open them in your running "mydaemon" and check them for inputs.

最后,应注意所有这些可以通过* nix OS的API在守护程序中完成是否运行发送到管道检查的操作,也可以使用例如以下命令在脚本中完成‘ps’,‘echo’等...

Finally, it should be noted that all of this check-if-running-send-to-pipe stuff can either be done in your daemon program, using the API of the *nix OS, or it can be done in a script by using e.g. 'ps', 'echo', etc...

这篇关于编写Unix守护进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆