| 219 | } |
| 220 | |
| 221 | int |
| 222 | pidfile_write(struct pidfh *pfh) |
| 223 | { |
| 224 | char pidstr[16]; |
| 225 | int error, fd; |
| 226 | |
| 227 | /* |
| 228 | * Check remembered descriptor, so we don't overwrite some other |
| 229 | * file if pidfile was closed and descriptor reused. |
| 230 | */ |
| 231 | errno = pidfile_verify(pfh); |
| 232 | if (errno != 0) { |
| 233 | /* |
| 234 | * Don't close descriptor, because we are not sure if it's ours. |
| 235 | */ |
| 236 | return (-1); |
| 237 | } |
| 238 | fd = pfh->pf_fd; |
| 239 | |
| 240 | /* |
| 241 | * Truncate PID file, so multiple calls of pidfile_write() are allowed. |
| 242 | */ |
| 243 | if (ftruncate(fd, 0) == -1) { |
| 244 | error = errno; |
| 245 | _pidfile_remove(pfh, 0); |
| 246 | errno = error; |
| 247 | return (-1); |
| 248 | } |
| 249 | |
| 250 | snprintf(pidstr, sizeof(pidstr), "%u", getpid()); |
| 251 | if (pwrite(fd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr)) { |
| 252 | error = errno; |
| 253 | _pidfile_remove(pfh, 0); |
| 254 | errno = error; |
| 255 | return (-1); |
| 256 | } |
| 257 | |
| 258 | return (0); |
| 259 | } |
| 260 | |
| 261 | int |
| 262 | pidfile_close(struct pidfh *pfh) |