74e79f5f8642d082d755f213ab271fb2078b30a1
[oweals/busybox.git] / ps.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini ps implementation(s) for busybox
4  *
5  * Copyright (C) 1999,2000 by Lineo, inc.  Written by Erik Andersen
6  * <andersen@lineo.com>, <andersee@debian.org>
7  *
8  *
9  * This contains _two_ implementations of ps for Linux.  One uses the
10  * traditional /proc virtual filesystem, and the other use the devps kernel
11  * driver (written by Erik Andersen to avoid using /proc thereby saving 100k+).
12  *
13  *
14  *
15  * This program is free software; you can redistribute it and/or modify it
16  * under the terms of the GNU General Public License as published by the Free
17  * Software Foundation; either version 2 of the License, or (at your option)
18  * any later version.
19  *
20  * This program is distributed in the hope that it will be useful, but WITHOUT
21  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
23  * more details.
24  *
25  * You should have received a copy of the GNU General Public License along with
26  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
27  * Place, Suite 330, Boston, MA 02111-1307 USA
28  *
29  */
30
31 #include "internal.h"
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <dirent.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <ctype.h>
38 #include <sys/ioctl.h>
39 #define BB_DECLARE_EXTERN
40 #define bb_need_help
41 #include "messages.c"
42
43 #define TERMINAL_WIDTH  79      /* not 80 in case terminal has linefold bug */
44
45
46
47 #if ! defined BB_FEATURE_USE_DEVPS_PATCH
48
49 /* The following is the first ps implementation --
50  * the one using the /proc virtual filesystem.
51  */
52
53 #if ! defined BB_FEATURE_USE_PROCFS
54 #error Sorry, I depend on the /proc filesystem right now.
55 #endif
56
57 typedef struct proc_s {
58         char
59          cmd[16];                                       /* basename of executable file in call to exec(2) */
60         int
61          ruid, rgid,                            /* real only (sorry) */
62          pid,                                           /* process id */
63          ppid;                                          /* pid of parent process */
64         char
65          state;                                         /* single-char code for process state (S=sleeping) */
66 } proc_t;
67
68
69
70 static int file2str(char *filename, char *ret, int cap)
71 {
72         int fd, num_read;
73
74         if ((fd = open(filename, O_RDONLY, 0)) == -1)
75                 return -1;
76         if ((num_read = read(fd, ret, cap - 1)) <= 0)
77                 return -1;
78         ret[num_read] = 0;
79         close(fd);
80         return num_read;
81 }
82
83
84 static void parse_proc_status(char *S, proc_t * P)
85 {
86         char *tmp;
87
88         memset(P->cmd, 0, sizeof P->cmd);
89         sscanf(S, "Name:\t%15c", P->cmd);
90         tmp = strchr(P->cmd, '\n');
91         if (tmp)
92                 *tmp = '\0';
93         tmp = strstr(S, "State");
94         sscanf(tmp, "State:\t%c", &P->state);
95
96         tmp = strstr(S, "Pid:");
97         if (tmp)
98                 sscanf(tmp, "Pid:\t%d\n" "PPid:\t%d\n", &P->pid, &P->ppid);
99         else
100                 errorMsg("Internal error!\n");
101
102         /* For busybox, ignoring effective, saved, etc */
103         tmp = strstr(S, "Uid:");
104         if (tmp)
105                 sscanf(tmp, "Uid:\t%d", &P->ruid);
106         else
107                 errorMsg("Internal error!\n");
108
109         tmp = strstr(S, "Gid:");
110         if (tmp)
111                 sscanf(tmp, "Gid:\t%d", &P->rgid);
112         else
113                 errorMsg("Internal error!\n");
114
115 }
116
117 const char ps_usage[] =
118         "ps\n"
119 #ifndef BB_FEATURE_TRIVIAL_HELP
120         "\nReport process status\n"
121         "\nThis version of ps accepts no options.\n"
122 #endif
123         ;
124
125 extern int ps_main(int argc, char **argv)
126 {
127         proc_t p;
128         DIR *dir;
129         FILE *file;
130         struct dirent *entry;
131         char path[32], sbuf[512];
132         char uidName[10] = "";
133         char groupName[10] = "";
134         int len, i, c;
135 #ifdef BB_FEATURE_AUTOWIDTH
136         struct winsize win = { 0, 0, 0, 0 };
137         int terminal_width = TERMINAL_WIDTH;
138 #else
139 #define terminal_width  TERMINAL_WIDTH
140 #endif
141
142
143
144         if (argc > 1 && strcmp(argv[1], dash_dash_help) == 0)
145                 usage(ps_usage);
146
147         dir = opendir("/proc");
148         if (!dir)
149                 fatalError("Can't open /proc\n");
150
151 #ifdef BB_FEATURE_AUTOWIDTH
152                 ioctl(fileno(stdout), TIOCGWINSZ, &win);
153                 if (win.ws_col > 0)
154                         terminal_width = win.ws_col - 1;
155 #endif
156
157         fprintf(stdout, "%5s  %-8s %-3s %5s %s\n", "PID", "Uid", "Gid",
158                         "State", "Command");
159         while ((entry = readdir(dir)) != NULL) {
160                 uidName[0] = '\0';
161                 groupName[0] = '\0';
162
163                 if (!isdigit(*entry->d_name))
164                         continue;
165                 sprintf(path, "/proc/%s/status", entry->d_name);
166                 if ((file2str(path, sbuf, sizeof sbuf)) != -1) {
167                         parse_proc_status(sbuf, &p);
168                 }
169
170                 /* Make some adjustments as needed */
171                 my_getpwuid(uidName, p.ruid);
172                 if (*uidName == '\0')
173                         sprintf(uidName, "%d", p.ruid);
174                 my_getgrgid(groupName, p.rgid);
175                 if (*groupName == '\0')
176                         sprintf(groupName, "%d", p.rgid);
177
178                 sprintf(path, "/proc/%s/cmdline", entry->d_name);
179                 file = fopen(path, "r");
180                 if (file == NULL)
181                         continue;
182                 i = 0;
183                 len = fprintf(stdout, "%5d %-8s %-8s %c ", p.pid, uidName, groupName,
184                                 p.state);
185                 while (((c = getc(file)) != EOF) && (i < (terminal_width-len))) {
186                         i++;
187                         if (c == '\0')
188                                 c = ' ';
189                         putc(c, stdout);
190                 }
191                 if (i == 0)
192                         fprintf(stdout, "[%s]", p.cmd);
193                 fprintf(stdout, "\n");
194         }
195         closedir(dir);
196         return(TRUE);
197 }
198
199
200 #else /* BB_FEATURE_USE_DEVPS_PATCH */
201
202
203 /* The following is the second ps implementation --
204  * this one uses the nifty new devps kernel device.
205  */
206
207 #include <linux/devps.h> /* For Erik's nifty devps device driver */
208
209
210 extern int ps_main(int argc, char **argv)
211 {
212         char device[] = "/dev/ps";
213         int i, j, len, fd;
214         pid_t num_pids;
215         pid_t* pid_array = NULL;
216         struct pid_info info;
217         char uidName[10] = "";
218         char groupName[10] = "";
219 #ifdef BB_FEATURE_AUTOWIDTH
220         struct winsize win = { 0, 0, 0, 0 };
221         int terminal_width = TERMINAL_WIDTH;
222 #else
223 #define terminal_width  TERMINAL_WIDTH
224 #endif
225
226         if (argc > 1 && **(argv + 1) == '-') 
227                 usage(ps_usage);
228
229         /* open device */ 
230         fd = open(device, O_RDONLY);
231         if (fd < 0) 
232                 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
233
234         /* Find out how many processes there are */
235         if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0) 
236                 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
237         
238         /* Allocate some memory -- grab a few extras just in case 
239          * some new processes start up while we wait. The kernel will
240          * just ignore any extras if we give it too many, and will trunc.
241          * the list if we give it too few.  */
242         pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
243         pid_array[0] = num_pids+10;
244
245         /* Now grab the pid list */
246         if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0) 
247                 fatalError("\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
248
249 #ifdef BB_FEATURE_AUTOWIDTH
250                 ioctl(fileno(stdout), TIOCGWINSZ, &win);
251                 if (win.ws_col > 0)
252                         terminal_width = win.ws_col - 1;
253 #endif
254
255         /* Print up a ps listing */
256         fprintf(stdout, "%5s  %-8s %-3s %5s %s\n", "PID", "Uid", "Gid",
257                         "State", "Command");
258
259         for (i=1; i<pid_array[0] ; i++) {
260                 uidName[0] = '\0';
261                 groupName[0] = '\0';
262             info.pid = pid_array[i];
263
264             if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
265                         fatalError("\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
266             
267                 /* Make some adjustments as needed */
268                 my_getpwuid(uidName, info.euid);
269                 if (*uidName == '\0')
270                         sprintf(uidName, "%ld", info.euid);
271                 my_getgrgid(groupName, info.egid);
272                 if (*groupName == '\0')
273                         sprintf(groupName, "%ld", info.egid);
274
275                 len = fprintf(stdout, "%5d %-8s %-8s %c ", info.pid, uidName, groupName, info.state);
276
277                 if (strlen(info.command_line) > 1) {
278                         for( j=0; j<(sizeof(info.command_line)-1) && j < (terminal_width-len); j++) {
279                                 if (*(info.command_line+j) == '\0' && *(info.command_line+j+1) != '\0') {
280                                         *(info.command_line+j) = ' ';
281                                 }
282                         }
283                         *(info.command_line+j) = '\0';
284                         fprintf(stdout, "%s\n", info.command_line);
285                 } else {
286                         fprintf(stdout, "[%s]\n", info.name);
287                 }
288         }
289
290         /* Free memory */
291         free( pid_array);
292
293         /* close device */
294         if (close (fd) != 0) 
295                 fatalError("close failed for `%s': %s\n", device, strerror (errno));
296  
297         exit (0);
298 }
299
300 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
301