1/*
2 * Copyright (c) 2017 Linux Test Project
3 *
4 * This program is free software;  you can redistribute it and/or modify
5 * it under the terms in version 2 of the GNU General Public License as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY;  without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
11 * the GNU General Public License for more details.
12 */
13
14#include <time.h>
15
16#include "posixtest.h"
17
18#ifdef __linux__
19# include <errno.h>
20# include <string.h>
21
22int tst_process_state_wait3(pid_t pid, const char state,
23	long maxwait_s)
24{
25	char proc_path[128], cur_state;
26	int wait_step_ms = 10;
27	struct timespec wait_step_ts;
28	long iteration, max_iterations = (maxwait_s * 1000) / wait_step_ms;
29
30	wait_step_ts.tv_sec = 0;
31	wait_step_ts.tv_nsec = wait_step_ms * 1000000;
32
33	snprintf(proc_path, sizeof(proc_path), "/proc/%i/stat", pid);
34
35	for (iteration = 0; iteration < max_iterations; iteration++) {
36		FILE *f = fopen(proc_path, "r");
37
38		if (!f) {
39			fprintf(stderr, "Failed to open '%s': %s\n",
40				proc_path, strerror(errno));
41			return 1;
42		}
43
44		if (fscanf(f, "%*i %*s %c", &cur_state) != 1) {
45			fclose(f);
46			fprintf(stderr, "Failed to read '%s': %s\n",
47				proc_path, strerror(errno));
48			return 1;
49		}
50		fclose(f);
51
52		if (state == cur_state)
53			return 0;
54
55		nanosleep(&wait_step_ts, NULL);
56	}
57	fprintf(stderr, "Reached max wait time\n");
58	return 1;
59}
60#else
61int tst_process_state_wait3(pid_t pid PTS_ATTRIBUTE_UNUSED,
62	const char state PTS_ATTRIBUTE_UNUSED, long maxwait_s)
63{
64	struct timespec maxwait_ts;
65
66	maxwait_ts.tv_sec = maxwait_s;
67	maxwait_ts.tv_nsec = 0;
68
69	nanosleep(&maxwait_ts, NULL);
70	return 0;
71}
72#endif
73