Home | History | Annotate | Download | only in include
      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 #ifdef __linux__
     15 # include <errno.h>
     16 # include <string.h>
     17 int tst_process_state_wait3(pid_t pid, const char state,
     18 	unsigned long maxwait_ms)
     19 {
     20 	char proc_path[128], cur_state;
     21 	int wait_step_ms = 10;
     22 	unsigned long waited_ms = 0;
     23 
     24 	snprintf(proc_path, sizeof(proc_path), "/proc/%i/stat", pid);
     25 
     26 	for (;;) {
     27 		FILE *f = fopen(proc_path, "r");
     28 
     29 		if (!f) {
     30 			fprintf(stderr, "Failed to open '%s': %s\n",
     31 				proc_path, strerror(errno));
     32 			return 1;
     33 		}
     34 
     35 		if (fscanf(f, "%*i %*s %c", &cur_state) != 1) {
     36 			fclose(f);
     37 			fprintf(stderr, "Failed to read '%s': %s\n",
     38 				proc_path, strerror(errno));
     39 			return 1;
     40 		}
     41 		fclose(f);
     42 
     43 		if (state == cur_state)
     44 			return 0;
     45 
     46 		usleep(wait_step_ms * 1000);
     47 		waited_ms += wait_step_ms;
     48 
     49 		if (waited_ms >= maxwait_ms) {
     50 			fprintf(stderr, "Reached max wait time\n");
     51 			return 1;
     52 		}
     53 	}
     54 }
     55 #else
     56 int tst_process_state_wait3(pid_t pid, const char state,
     57 	unsigned long maxwait_ms)
     58 {
     59 	usleep(maxwait_ms * 1000);
     60 	return 0;
     61 }
     62 #endif
     63