Re: [Fwd: Serious problem with mount(8)]

From: Dag-Erling Smørgrav <des_at_des.no>
Date: Wed, 23 May 2007 09:30:10 +0200
Joe Marcus Clarke <marcus_at_FreeBSD.org> writes:
> Dag-Erling Smørgrav <des_at_des.no> writes:
> > Better yet, extend the pidfile API with a function which reads the
> > contents of a PID file and also checks whether it's locked.
> I'd be happy to do this.  Is my approach with this code sound (i.e. can
> I simply port this to pidfile(3)), or should I take another approach?
> Thanks.

You expose yourself to all sorts of race conditions by opening the file
twice...  what you should do is something like (off the top of my head):

        fd = open(pidfile, O_RDONLY);
        fcntl(fd, F_GETLK, &fl)
        if (fl.l_type == F_UNLCK)
                return (-1)
        fstat(fd, &fsb);
        read(fd, buf, fsb.st_len);
        if (atoi(buf) != fl.l_pid)
                return (-1);
#ifdef OPTIONAL
        stat(pidfile, &sb);
        if (sb.st_dev != fsb.st_dev || sb.st_ino != fsb.st_ino)
                return (-1);
#endif
        return (fl.l_pid);

with appropriate error checking, of course.

DES
-- 
Dag-Erling Smørgrav - des_at_des.no
Received on Wed May 23 2007 - 05:30:15 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:39:10 UTC