[systemd-devel] sd_listen_fds: find file descriptor

Lennart Poettering lennart at poettering.net
Thu Dec 15 06:52:47 PST 2011


On Wed, 14.12.11 13:28, Michael D. Berger (m.d.berger at ieee.org) wrote:

> I quote the man page:
> 
>   Otherwise the number of file descriptors passed is returned. The
>   application may find them starting with file descriptor
>   SD_LISTEN_FDS_START, i.e. file descriptor 3
> 
> For example, assume sd_listen_fds returns 5.  Then I do somethiing like:
>  
>    int jj = 3;
>    for (; jj < 8; ++jj)
>       if (<sd_is_socket_inet says it is the right thing>)
>          break;
>    if (jj < 8)
>       <jj is a good handle>
> 
> Right?  If not, then what?

Hmm? You should usually consume all fds you get passed. And if you
cannot handle more than one, then exit quickly with an error
message. And if any of the fds is invalid, then print an error message
and leave, too.

This is what I'd usually use:


int fd, n;

n = sd_listen_fds();
if (n < 0)  {
        fprintf(stderr, "sd_listen_fds(): %s\n", strerror(-n));
        exit(1);
}

for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) {
        if (sd_is_socket_inet(fd, ...) <= 0) {
                fprintf(stderr, "Invalid socket passed.\n");
                exit(1);
        }

        /* do something with the fd... */
}

(This is for the generic case where the service can handle more than one
fd. If you can handle ony one, then check whether n == 1 and if it isn't
exit saying you can't deal with more than one fd.)

Lennart

-- 
Lennart Poettering - Red Hat, Inc.


More information about the systemd-devel mailing list