2 * copyright (c) 2007-2011 Emil Mikulic.
4 * pidfile.h: pidfile manglement
6 * Permission to use, copy, modify, and distribute this file for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29 static int pidfd
= -1;
30 static const char *pidname
= NULL
;
33 pidfile_create(const char *chroot_dir
, const char *filename
,
34 const char *privdrop_user
)
39 errx(1, "pidfile already created");
42 pw
= getpwnam(privdrop_user
);
46 errx(1, "getpwnam(\"%s\") failed: no such user", privdrop_user
);
48 err(1, "getpwnam(\"%s\") failed", privdrop_user
);
51 if (chdir(chroot_dir
) == -1)
52 err(1, "chdir(\"%s\") failed", chroot_dir
);
54 pidfd
= open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_EXCL
, 0600);
56 err(1, "couldn't not create pidfile");
57 if (chown(filename
, pw
->pw_uid
, pw
->pw_gid
) == -1)
58 err(1, "couldn't chown pidfile");
62 pidfile_write_close(void)
69 errx(1, "cannot write pidfile: not created");
72 str_appendf(s
, "%u\n", (unsigned int)getpid());
73 str_extract(s
, &len
, &buf
);
75 if (write(pidfd
, buf
, len
) != (int)len
)
76 err(1, "couldn't write to pidfile");
78 if (close(pidfd
) == -1)
79 warn("problem closing pidfile");
86 return; /* pidfile wasn't created */
87 if (unlink(pidname
) == -1)
88 warn("problem unlinking pidfile");
91 /* vim:set ts=3 sw=3 tw=78 et: */