开发者

Interacting with Application while it's running in C

I've been looking for an answer to this question for a while now. I have written a small, lightweight server and it runs just fine really. No problems there; however, there's some things I would like to do with the application while it's actually running. For example: server stop to obviously halt the server.

Perhaps I should be looking at making a daemon for my server? The platform it runs on is Linux, and I have no intentions of porting to non-POSIX platforms, so Windows isn't relevant here.

But yes, to summarize my question: how to make my application receive 'arguments' 开发者_如何学Pythonor 'tasks' from outside (such as the command line, or a different application)

Cheers in advance, as I know StackOverflow is always ready with a solid, quick answer,

/Jesse


There is a variety of options. One popular solution is to use POSIX-style signals. Basically you install a signal handler and react to signals.

If that is too simplistic (because e.g. you need to accept parameters), you could also let your daemon open a socket where it listens for commands. You then write a small helper program to send commands to the socket. You can also do something similar using a named pipe.

Basically what you are looking for is called Inter-process communication (IPC). The Wikipedia page may point you in the right direction.


You may be interested into looking into Signal Handling, which is a common method that applications such as the Apache web server use to handle requests like this.


On POSIX platforms, a simple way to control a running application is to use signals. For example, you could write a handler for the SIGUSR1 signal that does something specific in the context of your server. You can send a signal like this:

kill -SIGUSR1 $pid

where $pid is the pid of your running server. A limitation of the signal method is there isn't any direct way to send any other information along with the signal. However, indirectly the server can act upon a signal by reloading a configuration file, for example.

For more complex control, another way to control a running server is to embed a simple web server inside it. If you set up that web server to listen on port 8080 for example, you would be able to talk to it by going to

http://localhost:8080/

in your browser. This method allows a near infinite number of possibilities for monitoring and control.


Some answers, from easy to complex:

  • Use signal(3) handlers. Meant for this purpose to do something. The kill(1) command will transmit the signal from the outside.
  • Monitor a file for changes and inspect what's in there, do something depending on what's in there
  • Use an IPC protocol that allows other applications to talk to you. Broad topic, widely discussed on the web.
  • Make it a client/server architecture in which commands can be sent through TCP/UDP.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜