Pass -nostdlib -nostartfiles together with -r [BZ #31753]
[glibc.git] / support / support_process_state.c
blob062335234f89c9ae98f193fea88ed41b78c0f4d3
1 /* Wait for process state.
2 Copyright (C) 2020-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
19 #include <stdlib.h>
20 #include <time.h>
21 #include <string.h>
23 #include <array_length.h>
24 #include <intprops.h>
26 #include <support/process_state.h>
27 #include <support/xstdio.h>
28 #include <support/check.h>
30 void
31 support_process_state_wait (pid_t pid, enum support_process_state state)
33 #ifdef __linux__
34 /* For Linux it does a polling check on /proc/<pid>/status checking on
35 third field. */
37 /* It mimics the kernel states from fs/proc/array.c */
38 static const struct process_states
40 enum support_process_state s;
41 char v;
42 } process_states[] = {
43 { support_process_state_running, 'R' },
44 { support_process_state_sleeping, 'S' },
45 { support_process_state_disk_sleep, 'D' },
46 { support_process_state_stopped, 'T' },
47 { support_process_state_tracing_stop, 't' },
48 { support_process_state_dead, 'X' },
49 { support_process_state_zombie, 'Z' },
50 { support_process_state_parked, 'P' },
53 char spath[sizeof ("/proc/") + INT_STRLEN_BOUND (pid_t) + sizeof ("/status") + 1];
54 snprintf (spath, sizeof (spath), "/proc/%i/status", pid);
56 FILE *fstatus = xfopen (spath, "r");
57 char *line = NULL;
58 size_t linesiz = 0;
60 for (;;)
62 char cur_state = -1;
63 while (xgetline (&line, &linesiz, fstatus) > 0)
64 if (strncmp (line, "State:", strlen ("State:")) == 0)
66 TEST_COMPARE (sscanf (line, "%*s %c", &cur_state), 1);
67 break;
69 /* Fallback to nanosleep for invalid state. */
70 if (cur_state == -1)
71 break;
73 for (size_t i = 0; i < array_length (process_states); ++i)
74 if (state & process_states[i].s && cur_state == process_states[i].v)
76 free (line);
77 xfclose (fstatus);
78 return;
81 rewind (fstatus);
82 fflush (fstatus);
84 if (nanosleep (&(struct timespec) { 0, 10000000 }, NULL) != 0)
85 FAIL_EXIT1 ("nanosleep: %m");
88 free (line);
89 xfclose (fstatus);
90 /* Fallback to nanosleep if an invalid state is found. */
91 #endif
92 nanosleep (&(struct timespec) { 1, 0 }, NULL);