A small USV for ALIX boards with i2c support
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.

pidfile.c 1.2KB

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