Creating a Linux Daemon

Evan Martin martine at cs.washington.edu
Sat Dec 8 19:05:07 PST 2001


On Fri, Dec 07, 2001 at 11:50:45PM -0800, John Porter Simons wrote:

> But I have no idea how to do this. I wouldn't know whether to use pipes or

> FIFOs or signals or what... Does anyone know of a good book or web

> resource that provides an example of how to do this? I'm guessing that on

> startup, the program would write its process ID to a file somewhere, but I

> don't know how, from PHP for example, I could send data to the process at

> that ID, and how the program would know where to send the result.


I managed to figure out how to use Unix sockets just by reading some web
tutorials. It's hard to find any tutorials that aren't about TCP
sockets, but there's only a few differences.

Here's some code for binding the socket (to be done on the server side):
sockaddr_un saun = {0};

if ((_sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("socket"); return -1;
}

saun.sun_family = AF_UNIX;
strcpy(saun.sun_path, "/path/to/the/socket");

unlink(addr);
len = sizeof(saun.sun_family) + strlen(saun.sun_path);
if (bind(_sock, (sockaddr*)&saun, len) < 0) {
perror("bind"); return -1;
}

The relevant differences should be clear; note the call to unlink() to
remove the socket if it existed before-- for example, if the server
process quit without cleaning up.

I wrote the client for this project in Python, but it should be pretty clear:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect('/path/to/the/socket')


The final thing that REALLY confused me (as I was accustomed to TCP
sockets) is that your server process will get a SIGPIPE when the
connection closes (in addition to read() returning 0).
You can prevent this situation from killing your server by ignoring that
signal:
signal(SIGPIPE, SIG_IGN);


As I write this, I realize that this manpage will be helpful, too:
man 7 unix
(see also 'man 7 tcp').


With all of that said, all of my friends have highly recommended the
Stevens book (which someone else already posted about).

--
Evan Martin
martine at cs.washington.edu
http://neugierig.org


More information about the Linux mailing list