1 /* Wait for process state.
2 Copyright (C) 2020-2022 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/>. */
23 #include <array_length.h>
26 #include <support/process_state.h>
27 #include <support/xstdio.h>
28 #include <support/check.h>
31 support_process_state_wait (pid_t pid
, enum support_process_state state
)
34 /* For Linux it does a polling check on /proc/<pid>/status checking on
37 /* It mimics the kernel states from fs/proc/array.c */
38 static const struct process_states
40 enum support_process_state s
;
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");
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);
69 /* Fallback to nanosleep for invalid state. */
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
)
84 if (nanosleep (&(struct timespec
) { 0, 10000000 }, NULL
) != 0)
85 FAIL_EXIT1 ("nanosleep: %m");
90 /* Fallback to nanosleep if an invalid state is found. */
92 nanosleep (&(struct timespec
) { 1, 0 }, NULL
);