pidfile.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. #include "orconfig.h"
  6. #include "lib/process/pidfile.h"
  7. #include "lib/log/torlog.h"
  8. #ifdef HAVE_SYS_TYPES_H
  9. #include <sys/types.h>
  10. #endif
  11. #ifdef HAVE_UNISTD_H
  12. #include <unistd.h>
  13. #endif
  14. #include <errno.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. /** Write the current process ID, followed by NL, into <b>filename</b>.
  18. * Return 0 on success, -1 on failure.
  19. */
  20. int
  21. write_pidfile(const char *filename)
  22. {
  23. FILE *pidfile;
  24. if ((pidfile = fopen(filename, "w")) == NULL) {
  25. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  26. strerror(errno));
  27. return -1;
  28. } else {
  29. #ifdef _WIN32
  30. int pid = (int)_getpid();
  31. #else
  32. int pid = (int)getpid();
  33. #endif
  34. int rv = 0;
  35. if (fprintf(pidfile, "%d\n", pid) < 0)
  36. rv = -1;
  37. if (fclose(pidfile) < 0)
  38. rv = -1;
  39. return rv;
  40. }
  41. }