/*
* virpidfile.c: manipulation of pidfiles
*
- * Copyright (C) 2010-2011 Red Hat, Inc.
+ * Copyright (C) 2010-2012 Red Hat, Inc.
* Copyright (C) 2006, 2007 Binary Karma
* Copyright (C) 2006 Shuveb Hussain
*
{
int rc;
int fd;
- FILE *file = NULL;
+ char pidstr[INT_BUFSIZE_BOUND(pid)];
if ((fd = open(pidfile,
O_WRONLY | O_CREAT | O_TRUNC,
goto cleanup;
}
- if (!(file = VIR_FDOPEN(fd, "w"))) {
- rc = -errno;
- VIR_FORCE_CLOSE(fd);
- goto cleanup;
- }
+ snprintf(pidstr, sizeof(pidstr), "%lld", (long long) pid);
- if (fprintf(file, "%d", pid) < 0) {
+ if (safewrite(fd, pidstr, strlen(pidstr)) < 0) {
rc = -errno;
+ VIR_FORCE_CLOSE(fd);
goto cleanup;
}
rc = 0;
cleanup:
- if (VIR_FCLOSE(file) < 0)
+ if (VIR_CLOSE(fd) < 0)
rc = -errno;
return rc;
int virPidFileReadPath(const char *path,
pid_t *pid)
{
- FILE *file;
+ int fd;
int rc;
+ ssize_t bytes;
+ long long pid_value = 0;
+ char pidstr[INT_BUFSIZE_BOUND(pid_value)];
*pid = 0;
- if (!(file = fopen(path, "r"))) {
+ if ((fd = open(path, O_RDONLY)) < 0) {
rc = -errno;
goto cleanup;
}
- if (fscanf(file, "%d", pid) != 1) {
- rc = -EINVAL;
- VIR_FORCE_FCLOSE(file);
+ bytes = saferead(fd, pidstr, sizeof(pidstr));
+ if (bytes < 0) {
+ rc = -errno;
+ VIR_FORCE_CLOSE(fd);
goto cleanup;
}
+ pidstr[bytes] = '\0';
- if (VIR_FCLOSE(file) < 0) {
- rc = -errno;
+ if (virStrToLong_ll(pidstr, NULL, 10, &pid_value) < 0 ||
+ (pid_t) pid_value != pid_value) {
+ rc = -1;
goto cleanup;
}
+ *pid = pid_value;
rc = 0;
- cleanup:
+cleanup:
+ if (VIR_CLOSE(fd) < 0)
+ rc = -errno;
+
return rc;
}
/* Someone else must be racing with us, so try agin */
}
- snprintf(pidstr, sizeof(pidstr), "%u", (unsigned int)pid);
+ snprintf(pidstr, sizeof(pidstr), "%lld", (long long) pid);
if (safewrite(fd, pidstr, strlen(pidstr)) < 0) {
virReportSystemError(errno,