Line data Source code
1 : #include "../process.h"
2 : #include <unistd.h>
3 : #include <signal.h>
4 : #include <stdio.h>
5 : #include <string.h>
6 :
7 0 : pid_t platform_getpid(void) {
8 0 : return getpid();
9 : }
10 :
11 3 : int platform_pid_is_program(pid_t pid, const char *progname) {
12 : /* Check liveness with signal 0 (POSIX — Linux, macOS, Android) */
13 3 : if (kill(pid, 0) != 0)
14 3 : return 0;
15 :
16 : #ifdef __linux__
17 : /* Verify executable name via /proc/<pid>/comm */
18 0 : char path[64];
19 0 : snprintf(path, sizeof(path), "/proc/%d/comm", (int)pid);
20 0 : FILE *f = fopen(path, "r");
21 0 : if (!f)
22 0 : return 1; /* can't verify — conservatively assume it matches */
23 0 : char comm[256] = {0};
24 0 : if (fgets(comm, sizeof(comm), f)) {
25 0 : fclose(f);
26 : /* strip trailing newline */
27 0 : size_t len = strlen(comm);
28 0 : while (len > 0 && (comm[len - 1] == '\n' || comm[len - 1] == '\r'))
29 0 : comm[--len] = '\0';
30 0 : return strcmp(comm, progname) == 0;
31 : }
32 0 : fclose(f);
33 0 : return 1; /* can't verify — conservatively assume it matches */
34 : #else
35 : /* macOS / Android: process exists, assume it's our program.
36 : * A stale PID file from a crashed previous run is handled by the
37 : * caller checking the file's age or by the mismatch being rare. */
38 : (void)progname;
39 : return 1;
40 : #endif
41 : }
|