pidfile.c (1101B)
1 /* Copyright (c) 2003-2004, Roger Dingledine 2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. 3 * Copyright (c) 2007-2021, The Tor Project, Inc. */ 4 /* See LICENSE for licensing information */ 5 6 /** 7 * \file pidfile.c 8 * \brief Record this process's PID to disk. 9 **/ 10 11 #include "orconfig.h" 12 #include "lib/process/pidfile.h" 13 14 #include "lib/log/log.h" 15 16 #ifdef HAVE_SYS_TYPES_H 17 #include <sys/types.h> 18 #endif 19 #ifdef HAVE_UNISTD_H 20 #include <unistd.h> 21 #endif 22 23 #include <errno.h> 24 #include <stdio.h> 25 #include <string.h> 26 27 /** Write the current process ID, followed by NL, into <b>filename</b>. 28 * Return 0 on success, -1 on failure. 29 */ 30 int 31 write_pidfile(const char *filename) 32 { 33 FILE *pidfile; 34 35 if ((pidfile = fopen(filename, "w")) == NULL) { 36 log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename, 37 strerror(errno)); 38 return -1; 39 } else { 40 #ifdef _WIN32 41 int pid = (int)_getpid(); 42 #else 43 int pid = (int)getpid(); 44 #endif 45 int rv = 0; 46 if (fprintf(pidfile, "%d\n", pid) < 0) 47 rv = -1; 48 if (fclose(pidfile) < 0) 49 rv = -1; 50 return rv; 51 } 52 }