blob: 05e1e8aad48f0c7b64bf96c82d6db55f37183f1f [file] [log] [blame]
subrata_modak8bc4d772009-01-15 10:31:45 +00001/*
2 *
3 * Copyright (c) International Business Machines Corp., 2009
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program 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
13 * the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20/*
21 * DESCRIPTION
22 * get_max_pids(): Return the maximum number of pids for this system by
23 * reading /proc/sys/kernel/pid_max
24 *
vapier45a8ba02009-07-20 10:59:32 +000025 * get_free_pids(): Return number of free pids by subtracting the number
subrata_modak8bc4d772009-01-15 10:31:45 +000026 * of pids currently used ('ps -eT') from max_pids
27 */
28
29
subrata_modak8bc4d772009-01-15 10:31:45 +000030#include <fcntl.h>
subrata_modakfc3529d2009-07-07 14:32:03 +000031#include <limits.h>
subrata_modak8bc4d772009-01-15 10:31:45 +000032#include <sys/types.h>
subrata_modakfc3529d2009-07-07 14:32:03 +000033#include "test.h"
subrata_modak8bc4d772009-01-15 10:31:45 +000034
35#define BUFSIZE 512
36
37int get_max_pids(void)
38{
39#ifdef __linux__
40
41 FILE *f;
42 char buf[BUFSIZE];
43
44 f = fopen("/proc/sys/kernel/pid_max", "r");
45 if (!f) {
46 tst_resm(TBROK, "Could not open /proc/sys/kernel/pid_max");
47 return -1;
48 }
49 if (!fgets(buf, BUFSIZE, f)) {
50 fclose(f);
51 tst_resm(TBROK, "Could not read /proc/sys/kernel/pid_max");
52 return -1;
53 }
54 fclose(f);
55 return atoi(buf);
56#else
57 return SHRT_MAX;
58#endif
59}
60
61
62int get_free_pids(void)
63{
64 FILE *f;
yaberauneya4263e492009-11-09 05:52:26 +000065 int rc, used_pids, max_pids;
subrata_modak8bc4d772009-01-15 10:31:45 +000066
67 f = popen("ps -eT | wc -l", "r");
68 if (!f) {
69 tst_resm(TBROK, "Could not run 'ps' to calculate used "
70 "pids");
71 return -1;
72 }
yaberauneya4263e492009-11-09 05:52:26 +000073 rc = fscanf(f, "%i", &used_pids);
subrata_modak8bc4d772009-01-15 10:31:45 +000074 pclose(f);
75
yaberauneya4263e492009-11-09 05:52:26 +000076 if (rc != 1 || used_pids < 0) {
subrata_modak8bc4d772009-01-15 10:31:45 +000077 tst_resm(TBROK, "Could not read output of 'ps' to "
78 "calculate used pids");
79 return -1;
80 }
81
82 max_pids = get_max_pids();
83
84 if (max_pids < 0)
85 return -1;
86
87 return max_pids - used_pids;
88}
89