• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  *   Copyright (c) International Business Machines  Corp., 2009
4  *   Copyright (c) 2014 Oracle and/or its affiliates. All Rights Reserved.
5  *
6  *   This program is free software;  you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY;  without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
14  *   the GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program;  if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <sys/types.h>
24 #include "test.h"
25 #include "tst_pid.h"
26 #include "old_safe_file_ops.h"
27 
28 #define PID_MAX_PATH "/proc/sys/kernel/pid_max"
29 
tst_get_unused_pid_(void (* cleanup_fn)(void))30 pid_t tst_get_unused_pid_(void (*cleanup_fn) (void))
31 {
32 	pid_t pid;
33 
34 	SAFE_FILE_SCANF(cleanup_fn, PID_MAX_PATH, "%d", &pid);
35 
36 	return pid;
37 }
38 
tst_get_free_pids_(void (* cleanup_fn)(void))39 int tst_get_free_pids_(void (*cleanup_fn) (void))
40 {
41 	FILE *f;
42 	int rc, used_pids, max_pids;
43 
44 	f = popen("ps -eT | wc -l", "r");
45 	if (!f) {
46 		tst_resm(TBROK, "Could not run 'ps' to calculate used " "pids");
47 		return -1;
48 	}
49 	rc = fscanf(f, "%i", &used_pids);
50 	pclose(f);
51 
52 	if (rc != 1 || used_pids < 0) {
53 		tst_resm(TBROK, "Could not read output of 'ps' to "
54 			 "calculate used pids");
55 		return -1;
56 	}
57 
58 	SAFE_FILE_SCANF(cleanup_fn, PID_MAX_PATH, "%d", &max_pids);
59 
60 	/* max_pids contains the maximum PID + 1,
61 	 * used_pids contains used PIDs + 1,
62 	 * so this additional '1' is eliminated by the substraction */
63 	return max_pids - used_pids;
64 }
65