pidfile.c 1.1 KB

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