Commit 980f4e8d authored by Tycho Andersen's avatar Tycho Andersen Committed by Pavel Emelyanov

test: make write_pidfile atomic

This is useful so that hooks can do a $(cat $pidfile) or [ -f $pidfile ]
and rely on the result.
Signed-off-by: 's avatarTycho Andersen <tycho.andersen@canonical.com>
It-makes-sence-by: 's avatarAndrey Vagin <avagin@openvz.org>
Signed-off-by: 's avatarPavel Emelyanov <xemul@virtuozzo.com>
parent 27a481c8
...@@ -100,21 +100,39 @@ void test_ext_init(int argc, char **argv) ...@@ -100,21 +100,39 @@ void test_ext_init(int argc, char **argv)
int write_pidfile(int pid) int write_pidfile(int pid)
{ {
int fd; int fd = -1;
char tmp[] = ".zdtm.pidfile.XXXXXX";
fd = open(pidfile, O_CREAT | O_EXCL | O_WRONLY, 0666); fd = mkstemp(tmp);
if (fd == -1) { if (fd == -1) {
fprintf(stderr, "Can't create the file %s: %m\n", pidfile); fprintf(stderr, "Can't create the file %s: %m\n", tmp);
return -1; return -1;
} }
if (fchmod(fd, 0666) < 0) {
fprintf(stderr, "Can't fchmod %s: %m\n", tmp);
goto err_c;
}
if (dprintf(fd, "%d", pid) == -1) { if (dprintf(fd, "%d", pid) == -1) {
fprintf(stderr, "Can't write in the file %s: %m\n", pidfile); fprintf(stderr, "Can't write in the file %s: %m\n", tmp);
return -1; goto err_c;
} }
close(fd); close(fd);
if (rename(tmp, pidfile) < 0) {
fprintf(stderr, "Can't rename %s to %s: %m\n", tmp, pidfile);
goto err_u;
}
return 0; return 0;
err_c:
close(fd);
err_u:
unlink(tmp);
return -1;
} }
void test_init(int argc, char **argv) void test_init(int argc, char **argv)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment