QNAP-TS419p system daemon
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.1 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <errno.h>
  8. #include <signal.h>
  9. int pidfile_create(const char *filename)
  10. {
  11. int fd = open(filename, O_CREAT | O_EXCL | O_RDWR, 0644);
  12. if (fd < 0)
  13. return -1;
  14. char buf[8];
  15. int len = snprintf(buf, sizeof(buf), "%d", getpid());
  16. write(fd, buf, len);
  17. close(fd);
  18. return 0;
  19. }
  20. int pidfile_remove(const char *filename)
  21. {
  22. return unlink(filename);
  23. }
  24. pid_t pidfile_check(const char *filename, int remove_stale)
  25. {
  26. int fd = open(filename, O_RDWR);
  27. if (fd < 0) {
  28. if (errno == ENOENT) {
  29. errno = 0;
  30. return 0;
  31. }
  32. return -1;
  33. }
  34. char buf[9];
  35. int len = read(fd, buf, sizeof(buf) -1);
  36. buf[len] = '\0';
  37. close(fd);
  38. char *tmp;
  39. pid_t pid = strtol(buf, &tmp, 10);
  40. if (len == 0 || tmp == buf)
  41. pid = -1;
  42. /* just return the pid */
  43. if (!remove_stale)
  44. return pid;
  45. /* invalid pid, remove stale file */
  46. if (pid == -1) {
  47. pidfile_remove(filename);
  48. return 0;
  49. }
  50. /* check if pid is still running */
  51. if (kill(pid, 0) == 0 || errno != ESRCH) {
  52. errno = 0;
  53. return pid;
  54. }
  55. errno = 0;
  56. pidfile_remove(filename);
  57. return 0;
  58. }