1 /* Wait for process state.
2 Copyright (C) 2020 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>
25 #include <support/process_state.h>
26 #include <support/xstdio.h>
27 #include <support/check.h>
30 support_process_state_wait (pid_t pid
, enum support_process_state state
)
33 /* For Linux it does a polling check on /proc/<pid>/status checking on
36 /* It mimics the kernel states from fs/proc/array.c */
37 static const struct process_states
39 enum support_process_state s
;
41 } process_states
[] = {
42 { support_process_state_running
, 'R' },
43 { support_process_state_sleeping
, 'S' },
44 { support_process_state_disk_sleep
, 'D' },
45 { support_process_state_stopped
, 'T' },
46 { support_process_state_tracing_stop
, 't' },
47 { support_process_state_dead
, 'X' },
48 { support_process_state_zombie
, 'Z' },
49 { support_process_state_parked
, 'P' },
52 char spath
[sizeof ("/proc/" + 3) * sizeof (pid_t
) + sizeof ("/status") + 1];
53 snprintf (spath
, sizeof (spath
), "/proc/%i/status", pid
);
55 FILE *fstatus
= xfopen (spath
, "r");
62 while (xgetline (&line
, &linesiz
, fstatus
) != -1)
63 if (strncmp (line
, "State:", strlen ("State:")) == 0)
65 TEST_COMPARE (sscanf (line
, "%*s %c", &cur_state
), 1);
68 /* Fallback to nanosleep for invalid state. */
72 for (size_t i
= 0; i
< array_length (process_states
); ++i
)
73 if (state
& process_states
[i
].s
&& cur_state
== process_states
[i
].v
)
83 if (nanosleep (&(struct timespec
) { 0, 10000000 }, NULL
) != 0)
84 FAIL_EXIT1 ("nanosleep: %m");
89 /* Fallback to nanosleep if an invalid state is found. */
91 nanosleep (&(struct timespec
) { 2, 0 }, NULL
);