xref: /aosp_15_r20/external/ltp/lib/tst_thread_state.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1*49cdfc7eSAndroid Build Coastguard Worker // SPDX-License-Identifier: GPL-2.0-or-later
2*49cdfc7eSAndroid Build Coastguard Worker /*
3*49cdfc7eSAndroid Build Coastguard Worker  * Copyright (C) 2022 SUSE LLC Andrea Cervesato <[email protected]>
4*49cdfc7eSAndroid Build Coastguard Worker  */
5*49cdfc7eSAndroid Build Coastguard Worker 
6*49cdfc7eSAndroid Build Coastguard Worker #include <stdio.h>
7*49cdfc7eSAndroid Build Coastguard Worker #include <unistd.h>
8*49cdfc7eSAndroid Build Coastguard Worker #include <string.h>
9*49cdfc7eSAndroid Build Coastguard Worker #include <errno.h>
10*49cdfc7eSAndroid Build Coastguard Worker 
11*49cdfc7eSAndroid Build Coastguard Worker #include "tst_safe_file_ops.h"
12*49cdfc7eSAndroid Build Coastguard Worker #include "tst_process_state.h"
13*49cdfc7eSAndroid Build Coastguard Worker 
tst_thread_state_wait(pid_t tid,const char state,unsigned int msec_timeout)14*49cdfc7eSAndroid Build Coastguard Worker int tst_thread_state_wait(pid_t tid, const char state,
15*49cdfc7eSAndroid Build Coastguard Worker 			  unsigned int msec_timeout)
16*49cdfc7eSAndroid Build Coastguard Worker {
17*49cdfc7eSAndroid Build Coastguard Worker 	char proc_path[128], cur_state;
18*49cdfc7eSAndroid Build Coastguard Worker 	unsigned int msecs = 0;
19*49cdfc7eSAndroid Build Coastguard Worker 
20*49cdfc7eSAndroid Build Coastguard Worker 	snprintf(proc_path, sizeof(proc_path), "/proc/self/task/%i/stat", tid);
21*49cdfc7eSAndroid Build Coastguard Worker 
22*49cdfc7eSAndroid Build Coastguard Worker 	for (;;) {
23*49cdfc7eSAndroid Build Coastguard Worker 		SAFE_FILE_SCANF(proc_path, "%*[^)]%*c %c", &cur_state);
24*49cdfc7eSAndroid Build Coastguard Worker 
25*49cdfc7eSAndroid Build Coastguard Worker 		if (state == cur_state)
26*49cdfc7eSAndroid Build Coastguard Worker 			break;
27*49cdfc7eSAndroid Build Coastguard Worker 
28*49cdfc7eSAndroid Build Coastguard Worker 		usleep(1000);
29*49cdfc7eSAndroid Build Coastguard Worker 		msecs += 1;
30*49cdfc7eSAndroid Build Coastguard Worker 
31*49cdfc7eSAndroid Build Coastguard Worker 		if (msec_timeout && msecs >= msec_timeout) {
32*49cdfc7eSAndroid Build Coastguard Worker 			errno = ETIMEDOUT;
33*49cdfc7eSAndroid Build Coastguard Worker 			return -1;
34*49cdfc7eSAndroid Build Coastguard Worker 		}
35*49cdfc7eSAndroid Build Coastguard Worker 	}
36*49cdfc7eSAndroid Build Coastguard Worker 
37*49cdfc7eSAndroid Build Coastguard Worker 	return 0;
38*49cdfc7eSAndroid Build Coastguard Worker }
39