3
0

ps.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini ps implementation(s) for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. * Fix for SELinux Support:(c)2007 Hiroshi Shinji <shiroshi@my.email.ne.jp>
  7. * (c)2007 Yuichi Nakamura <ynakam@hitachisoft.jp>
  8. *
  9. * Licensed under GPLv2, see file LICENSE in this source tree.
  10. */
  11. //usage:#if ENABLE_DESKTOP
  12. //usage:
  13. //usage:#define ps_trivial_usage
  14. //usage: "[-o COL1,COL2=HEADER]" IF_FEATURE_SHOW_THREADS(" [-T]")
  15. //usage:#define ps_full_usage "\n\n"
  16. //usage: "Show list of processes\n"
  17. //usage: "\n -o COL1,COL2=HEADER Select columns for display"
  18. //usage: IF_FEATURE_SHOW_THREADS(
  19. //usage: "\n -T Show threads"
  20. //usage: )
  21. //usage:
  22. //usage:#else /* !ENABLE_DESKTOP */
  23. //usage:
  24. //usage:#if !ENABLE_SELINUX && !ENABLE_FEATURE_PS_WIDE
  25. //usage:#define USAGE_PS "\nThis version of ps accepts no options"
  26. //usage:#else
  27. //usage:#define USAGE_PS ""
  28. //usage:#endif
  29. //usage:
  30. //usage:#define ps_trivial_usage
  31. //usage: ""
  32. //usage:#define ps_full_usage "\n\n"
  33. //usage: "Show list of processes\n"
  34. //usage: USAGE_PS
  35. //usage: IF_SELINUX(
  36. //usage: "\n -Z Show selinux context"
  37. //usage: )
  38. //usage: IF_FEATURE_PS_WIDE(
  39. //usage: "\n w Wide output"
  40. //usage: )
  41. //usage: IF_FEATURE_PS_LONG(
  42. //usage: "\n l Long output"
  43. //usage: )
  44. //usage: IF_FEATURE_SHOW_THREADS(
  45. //usage: "\n T Show threads"
  46. //usage: )
  47. //usage:
  48. //usage:#endif /* ENABLE_DESKTOP */
  49. //usage:
  50. //usage:#define ps_example_usage
  51. //usage: "$ ps\n"
  52. //usage: " PID Uid Gid State Command\n"
  53. //usage: " 1 root root S init\n"
  54. //usage: " 2 root root S [kflushd]\n"
  55. //usage: " 3 root root S [kupdate]\n"
  56. //usage: " 4 root root S [kpiod]\n"
  57. //usage: " 5 root root S [kswapd]\n"
  58. //usage: " 742 andersen andersen S [bash]\n"
  59. //usage: " 743 andersen andersen S -bash\n"
  60. //usage: " 745 root root S [getty]\n"
  61. //usage: " 2990 andersen andersen R ps\n"
  62. #include "libbb.h"
  63. #include "common_bufsiz.h"
  64. #ifdef __linux__
  65. # include <sys/sysinfo.h>
  66. #endif
  67. /* Absolute maximum on output line length */
  68. enum { MAX_WIDTH = 2*1024 };
  69. #if ENABLE_FEATURE_PS_TIME || ENABLE_FEATURE_PS_LONG
  70. static unsigned long get_uptime(void)
  71. {
  72. #ifdef __linux__
  73. struct sysinfo info;
  74. if (sysinfo(&info) < 0)
  75. return 0;
  76. return info.uptime;
  77. #elif 1
  78. unsigned long uptime;
  79. char buf[sizeof(uptime)*3 + 2];
  80. /* /proc/uptime is "UPTIME_SEC.NN IDLE_SEC.NN\n"
  81. * (where IDLE is cumulative over all CPUs)
  82. */
  83. if (open_read_close("/proc/uptime", buf, sizeof(buf)) <= 0)
  84. bb_perror_msg_and_die("can't read '%s'", "/proc/uptime");
  85. buf[sizeof(buf)-1] = '\0';
  86. sscanf(buf, "%lu", &uptime);
  87. return uptime;
  88. #else
  89. struct timespec ts;
  90. if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
  91. return 0;
  92. return ts.tv_sec;
  93. #endif
  94. }
  95. #endif
  96. #if ENABLE_DESKTOP
  97. #include <sys/times.h> /* for times() */
  98. #ifndef AT_CLKTCK
  99. # define AT_CLKTCK 17
  100. #endif
  101. /* TODO:
  102. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
  103. * specifies (for XSI-conformant systems) following default columns
  104. * (l and f mark columns shown with -l and -f respectively):
  105. * F l Flags (octal and additive) associated with the process (??)
  106. * S l The state of the process
  107. * UID f,l The user ID; the login name is printed with -f
  108. * PID The process ID
  109. * PPID f,l The parent process
  110. * C f,l Processor utilization
  111. * PRI l The priority of the process; higher numbers mean lower priority
  112. * NI l Nice value
  113. * ADDR l The address of the process
  114. * SZ l The size in blocks of the core image of the process
  115. * WCHAN l The event for which the process is waiting or sleeping
  116. * STIME f Starting time of the process
  117. * TTY The controlling terminal for the process
  118. * TIME The cumulative execution time for the process
  119. * CMD The command name; the full command line is shown with -f
  120. */
  121. typedef struct {
  122. uint16_t width;
  123. char name6[6];
  124. const char *header;
  125. void (*f)(char *buf, int size, const procps_status_t *ps);
  126. int ps_flags;
  127. } ps_out_t;
  128. struct globals {
  129. ps_out_t* out;
  130. int out_cnt;
  131. int print_header;
  132. int need_flags;
  133. char *buffer;
  134. unsigned terminal_width;
  135. #if ENABLE_FEATURE_PS_TIME
  136. unsigned kernel_HZ;
  137. unsigned long seconds_since_boot;
  138. #endif
  139. } FIX_ALIASING;
  140. #define G (*(struct globals*)bb_common_bufsiz1)
  141. #define out (G.out )
  142. #define out_cnt (G.out_cnt )
  143. #define print_header (G.print_header )
  144. #define need_flags (G.need_flags )
  145. #define buffer (G.buffer )
  146. #define terminal_width (G.terminal_width )
  147. #define kernel_HZ (G.kernel_HZ )
  148. #define INIT_G() do { setup_common_bufsiz(); } while (0)
  149. #if ENABLE_FEATURE_PS_TIME
  150. /* for ELF executables, notes are pushed before environment and args */
  151. static uintptr_t find_elf_note(uintptr_t findme)
  152. {
  153. uintptr_t *ep = (uintptr_t *) environ;
  154. while (*ep++)
  155. continue;
  156. while (*ep) {
  157. if (ep[0] == findme) {
  158. return ep[1];
  159. }
  160. ep += 2;
  161. }
  162. return -1;
  163. }
  164. #if ENABLE_FEATURE_PS_UNUSUAL_SYSTEMS
  165. static unsigned get_HZ_by_waiting(void)
  166. {
  167. struct timeval tv1, tv2;
  168. unsigned t1, t2, r, hz;
  169. unsigned cnt = cnt; /* for compiler */
  170. int diff;
  171. r = 0;
  172. /* Wait for times() to reach new tick */
  173. t1 = times(NULL);
  174. do {
  175. t2 = times(NULL);
  176. } while (t2 == t1);
  177. gettimeofday(&tv2, NULL);
  178. do {
  179. t1 = t2;
  180. tv1.tv_usec = tv2.tv_usec;
  181. /* Wait exactly one times() tick */
  182. do {
  183. t2 = times(NULL);
  184. } while (t2 == t1);
  185. gettimeofday(&tv2, NULL);
  186. /* Calculate ticks per sec, rounding up to even */
  187. diff = tv2.tv_usec - tv1.tv_usec;
  188. if (diff <= 0) diff += 1000000;
  189. hz = 1000000u / (unsigned)diff;
  190. hz = (hz+1) & ~1;
  191. /* Count how many same hz values we saw */
  192. if (r != hz) {
  193. r = hz;
  194. cnt = 0;
  195. }
  196. cnt++;
  197. } while (cnt < 3); /* exit if saw 3 same values */
  198. return r;
  199. }
  200. #else
  201. static inline unsigned get_HZ_by_waiting(void)
  202. {
  203. /* Better method? */
  204. return 100;
  205. }
  206. #endif
  207. static unsigned get_kernel_HZ(void)
  208. {
  209. if (kernel_HZ)
  210. return kernel_HZ;
  211. /* Works for ELF only, Linux 2.4.0+ */
  212. kernel_HZ = find_elf_note(AT_CLKTCK);
  213. if (kernel_HZ == (unsigned)-1)
  214. kernel_HZ = get_HZ_by_waiting();
  215. G.seconds_since_boot = get_uptime();
  216. return kernel_HZ;
  217. }
  218. #endif
  219. /* Print value to buf, max size+1 chars (including trailing '\0') */
  220. static void func_user(char *buf, int size, const procps_status_t *ps)
  221. {
  222. #if 1
  223. safe_strncpy(buf, get_cached_username(ps->uid), size+1);
  224. #else
  225. /* "compatible" version, but it's larger */
  226. /* procps 2.18 shows numeric UID if name overflows the field */
  227. /* TODO: get_cached_username() returns numeric string if
  228. * user has no passwd record, we will display it
  229. * left-justified here; too long usernames are shown
  230. * as _right-justified_ IDs. Is it worth fixing? */
  231. const char *user = get_cached_username(ps->uid);
  232. if (strlen(user) <= size)
  233. safe_strncpy(buf, user, size+1);
  234. else
  235. sprintf(buf, "%*u", size, (unsigned)ps->uid);
  236. #endif
  237. }
  238. static void func_group(char *buf, int size, const procps_status_t *ps)
  239. {
  240. safe_strncpy(buf, get_cached_groupname(ps->gid), size+1);
  241. }
  242. static void func_comm(char *buf, int size, const procps_status_t *ps)
  243. {
  244. safe_strncpy(buf, ps->comm, size+1);
  245. }
  246. static void func_state(char *buf, int size, const procps_status_t *ps)
  247. {
  248. safe_strncpy(buf, ps->state, size+1);
  249. }
  250. static void func_args(char *buf, int size, const procps_status_t *ps)
  251. {
  252. read_cmdline(buf, size+1, ps->pid, ps->comm);
  253. }
  254. static void func_pid(char *buf, int size, const procps_status_t *ps)
  255. {
  256. sprintf(buf, "%*u", size, ps->pid);
  257. }
  258. static void func_ppid(char *buf, int size, const procps_status_t *ps)
  259. {
  260. sprintf(buf, "%*u", size, ps->ppid);
  261. }
  262. static void func_pgid(char *buf, int size, const procps_status_t *ps)
  263. {
  264. sprintf(buf, "%*u", size, ps->pgid);
  265. }
  266. static void put_lu(char *buf, int size, unsigned long u)
  267. {
  268. char buf4[5];
  269. /* see http://en.wikipedia.org/wiki/Tera */
  270. smart_ulltoa4(u, buf4, " mgtpezy")[0] = '\0';
  271. sprintf(buf, "%.*s", size, buf4);
  272. }
  273. static void func_vsz(char *buf, int size, const procps_status_t *ps)
  274. {
  275. put_lu(buf, size, ps->vsz);
  276. }
  277. static void func_rss(char *buf, int size, const procps_status_t *ps)
  278. {
  279. put_lu(buf, size, ps->rss);
  280. }
  281. static void func_tty(char *buf, int size, const procps_status_t *ps)
  282. {
  283. buf[0] = '?';
  284. buf[1] = '\0';
  285. if (ps->tty_major) /* tty field of "0" means "no tty" */
  286. snprintf(buf, size+1, "%u,%u", ps->tty_major, ps->tty_minor);
  287. }
  288. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  289. static void func_rgroup(char *buf, int size, const procps_status_t *ps)
  290. {
  291. safe_strncpy(buf, get_cached_groupname(ps->rgid), size+1);
  292. }
  293. static void func_ruser(char *buf, int size, const procps_status_t *ps)
  294. {
  295. safe_strncpy(buf, get_cached_username(ps->ruid), size+1);
  296. }
  297. static void func_nice(char *buf, int size, const procps_status_t *ps)
  298. {
  299. sprintf(buf, "%*d", size, ps->niceness);
  300. }
  301. #endif
  302. #if ENABLE_FEATURE_PS_TIME
  303. static void func_etime(char *buf, int size, const procps_status_t *ps)
  304. {
  305. /* elapsed time [[dd-]hh:]mm:ss; here only mm:ss */
  306. unsigned long mm;
  307. unsigned ss;
  308. mm = ps->start_time / get_kernel_HZ();
  309. /* must be after get_kernel_HZ()! */
  310. mm = G.seconds_since_boot - mm;
  311. ss = mm % 60;
  312. mm /= 60;
  313. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  314. }
  315. static void func_time(char *buf, int size, const procps_status_t *ps)
  316. {
  317. /* cumulative time [[dd-]hh:]mm:ss; here only mm:ss */
  318. unsigned long mm;
  319. unsigned ss;
  320. mm = (ps->utime + ps->stime) / get_kernel_HZ();
  321. ss = mm % 60;
  322. mm /= 60;
  323. snprintf(buf, size+1, "%3lu:%02u", mm, ss);
  324. }
  325. #endif
  326. #if ENABLE_SELINUX
  327. static void func_label(char *buf, int size, const procps_status_t *ps)
  328. {
  329. safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
  330. }
  331. #endif
  332. /*
  333. static void func_nice(char *buf, int size, const procps_status_t *ps)
  334. {
  335. ps->???
  336. }
  337. static void func_pcpu(char *buf, int size, const procps_status_t *ps)
  338. {
  339. }
  340. */
  341. static const ps_out_t out_spec[] = {
  342. /* Mandated by http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html: */
  343. { 8 , "user" ,"USER" ,func_user ,PSSCAN_UIDGID },
  344. { 8 , "group" ,"GROUP" ,func_group ,PSSCAN_UIDGID },
  345. { 16 , "comm" ,"COMMAND",func_comm ,PSSCAN_COMM },
  346. { MAX_WIDTH , "args" ,"COMMAND",func_args ,PSSCAN_COMM },
  347. { 5 , "pid" ,"PID" ,func_pid ,PSSCAN_PID },
  348. { 5 , "ppid" ,"PPID" ,func_ppid ,PSSCAN_PPID },
  349. { 5 , "pgid" ,"PGID" ,func_pgid ,PSSCAN_PGID },
  350. #if ENABLE_FEATURE_PS_TIME
  351. { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_START_TIME },
  352. #endif
  353. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  354. { 5 , "nice" ,"NI" ,func_nice ,PSSCAN_NICE },
  355. { 8 , "rgroup","RGROUP" ,func_rgroup,PSSCAN_RUIDGID },
  356. { 8 , "ruser" ,"RUSER" ,func_ruser ,PSSCAN_RUIDGID },
  357. // { 5 , "pcpu" ,"%CPU" ,func_pcpu ,PSSCAN_ },
  358. #endif
  359. #if ENABLE_FEATURE_PS_TIME
  360. { 6 , "time" ,"TIME" ,func_time ,PSSCAN_STIME | PSSCAN_UTIME },
  361. #endif
  362. { 6 , "tty" ,"TT" ,func_tty ,PSSCAN_TTY },
  363. { 4 , "vsz" ,"VSZ" ,func_vsz ,PSSCAN_VSZ },
  364. /* Not mandated, but useful: */
  365. { 4 , "stat" ,"STAT" ,func_state ,PSSCAN_STATE },
  366. { 4 , "rss" ,"RSS" ,func_rss ,PSSCAN_RSS },
  367. #if ENABLE_SELINUX
  368. { 35 , "label" ,"LABEL" ,func_label ,PSSCAN_CONTEXT },
  369. #endif
  370. };
  371. static ps_out_t* new_out_t(void)
  372. {
  373. out = xrealloc_vector(out, 2, out_cnt);
  374. return &out[out_cnt++];
  375. }
  376. static const ps_out_t* find_out_spec(const char *name)
  377. {
  378. unsigned i;
  379. char buf[ARRAY_SIZE(out_spec)*7 + 1];
  380. char *p = buf;
  381. for (i = 0; i < ARRAY_SIZE(out_spec); i++) {
  382. if (strncmp(name, out_spec[i].name6, 6) == 0)
  383. return &out_spec[i];
  384. p += sprintf(p, "%.6s,", out_spec[i].name6);
  385. }
  386. p[-1] = '\0';
  387. bb_error_msg_and_die("bad -o argument '%s', supported arguments: %s", name, buf);
  388. }
  389. static void parse_o(char* opt)
  390. {
  391. ps_out_t* new;
  392. // POSIX: "-o is blank- or comma-separated list" (FIXME)
  393. char *comma, *equal;
  394. while (1) {
  395. comma = strchr(opt, ',');
  396. equal = strchr(opt, '=');
  397. if (comma && (!equal || equal > comma)) {
  398. *comma = '\0';
  399. *new_out_t() = *find_out_spec(opt);
  400. *comma = ',';
  401. opt = comma + 1;
  402. continue;
  403. }
  404. break;
  405. }
  406. // opt points to last spec in comma separated list.
  407. // This one can have =HEADER part.
  408. new = new_out_t();
  409. if (equal)
  410. *equal = '\0';
  411. *new = *find_out_spec(opt);
  412. if (equal) {
  413. *equal = '=';
  414. new->header = equal + 1;
  415. // POSIX: the field widths shall be ... at least as wide as
  416. // the header text (default or overridden value).
  417. // If the header text is null, such as -o user=,
  418. // the field width shall be at least as wide as the
  419. // default header text
  420. if (new->header[0]) {
  421. new->width = strlen(new->header);
  422. print_header = 1;
  423. }
  424. } else
  425. print_header = 1;
  426. }
  427. static void alloc_line_buffer(void)
  428. {
  429. int i;
  430. int width = 0;
  431. for (i = 0; i < out_cnt; i++) {
  432. need_flags |= out[i].ps_flags;
  433. if (out[i].header[0]) {
  434. print_header = 1;
  435. }
  436. width += out[i].width + 1; /* "FIELD " */
  437. if ((int)(width - terminal_width) > 0) {
  438. /* The rest does not fit on the screen */
  439. //out[i].width -= (width - terminal_width - 1);
  440. out_cnt = i + 1;
  441. break;
  442. }
  443. }
  444. #if ENABLE_SELINUX
  445. if (!is_selinux_enabled())
  446. need_flags &= ~PSSCAN_CONTEXT;
  447. #endif
  448. buffer = xmalloc(width + 1); /* for trailing \0 */
  449. }
  450. static void format_header(void)
  451. {
  452. int i;
  453. ps_out_t* op;
  454. char *p;
  455. if (!print_header)
  456. return;
  457. p = buffer;
  458. i = 0;
  459. if (out_cnt) {
  460. while (1) {
  461. op = &out[i];
  462. if (++i == out_cnt) /* do not pad last field */
  463. break;
  464. p += sprintf(p, "%-*s ", op->width, op->header);
  465. }
  466. strcpy(p, op->header);
  467. }
  468. printf("%.*s\n", terminal_width, buffer);
  469. }
  470. static void format_process(const procps_status_t *ps)
  471. {
  472. int i, len;
  473. char *p = buffer;
  474. i = 0;
  475. if (out_cnt) while (1) {
  476. out[i].f(p, out[i].width, ps);
  477. // POSIX: Any field need not be meaningful in all
  478. // implementations. In such a case a hyphen ( '-' )
  479. // should be output in place of the field value.
  480. if (!p[0]) {
  481. p[0] = '-';
  482. p[1] = '\0';
  483. }
  484. len = strlen(p);
  485. p += len;
  486. len = out[i].width - len + 1;
  487. if (++i == out_cnt) /* do not pad last field */
  488. break;
  489. p += sprintf(p, "%*s", len, "");
  490. }
  491. printf("%.*s\n", terminal_width, buffer);
  492. }
  493. #if ENABLE_SELINUX
  494. # define SELINUX_O_PREFIX "label,"
  495. # define DEFAULT_O_STR (SELINUX_O_PREFIX "pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  496. #else
  497. # define DEFAULT_O_STR ("pid,user" IF_FEATURE_PS_TIME(",time") ",args")
  498. #endif
  499. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  500. int ps_main(int argc UNUSED_PARAM, char **argv)
  501. {
  502. procps_status_t *p;
  503. llist_t* opt_o = NULL;
  504. char default_o[sizeof(DEFAULT_O_STR)];
  505. int opt;
  506. enum {
  507. OPT_Z = (1 << 0),
  508. OPT_o = (1 << 1),
  509. OPT_a = (1 << 2),
  510. OPT_A = (1 << 3),
  511. OPT_d = (1 << 4),
  512. OPT_e = (1 << 5),
  513. OPT_f = (1 << 6),
  514. OPT_l = (1 << 7),
  515. OPT_T = (1 << 8) * ENABLE_FEATURE_SHOW_THREADS,
  516. };
  517. INIT_G();
  518. // POSIX:
  519. // -a Write information for all processes associated with terminals
  520. // Implementations may omit session leaders from this list
  521. // -A Write information for all processes
  522. // -d Write information for all processes, except session leaders
  523. // -e Write information for all processes (equivalent to -A)
  524. // -f Generate a full listing
  525. // -l Generate a long listing
  526. // -o col1,col2,col3=header
  527. // Select which columns to display
  528. /* We allow (and ignore) most of the above. FIXME.
  529. * -T is picked for threads (POSIX hasn't standardized it).
  530. * procps v3.2.7 supports -T and shows tids as SPID column,
  531. * it also supports -L where it shows tids as LWP column.
  532. */
  533. opt_complementary = "o::";
  534. opt = getopt32(argv, "Zo:aAdefl"IF_FEATURE_SHOW_THREADS("T"), &opt_o);
  535. if (opt_o) {
  536. do {
  537. parse_o(llist_pop(&opt_o));
  538. } while (opt_o);
  539. } else {
  540. /* Below: parse_o() needs char*, NOT const char*,
  541. * can't pass it constant string. Need to make a copy first.
  542. */
  543. #if ENABLE_SELINUX
  544. if (!(opt & OPT_Z) || !is_selinux_enabled()) {
  545. /* no -Z or no SELinux: do not show LABEL */
  546. strcpy(default_o, DEFAULT_O_STR + sizeof(SELINUX_O_PREFIX)-1);
  547. } else
  548. #endif
  549. {
  550. strcpy(default_o, DEFAULT_O_STR);
  551. }
  552. parse_o(default_o);
  553. }
  554. #if ENABLE_FEATURE_SHOW_THREADS
  555. if (opt & OPT_T)
  556. need_flags |= PSSCAN_TASKS;
  557. #endif
  558. /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
  559. * and such large widths */
  560. terminal_width = MAX_WIDTH;
  561. if (isatty(1)) {
  562. terminal_width = get_terminal_width(0);
  563. if (--terminal_width > MAX_WIDTH)
  564. terminal_width = MAX_WIDTH;
  565. }
  566. alloc_line_buffer();
  567. format_header();
  568. p = NULL;
  569. while ((p = procps_scan(p, need_flags)) != NULL) {
  570. format_process(p);
  571. }
  572. return EXIT_SUCCESS;
  573. }
  574. #else /* !ENABLE_DESKTOP */
  575. int ps_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  576. int ps_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  577. {
  578. procps_status_t *p;
  579. int psscan_flags = PSSCAN_PID | PSSCAN_UIDGID
  580. | PSSCAN_STATE | PSSCAN_VSZ | PSSCAN_COMM;
  581. unsigned terminal_width IF_NOT_FEATURE_PS_WIDE(= 79);
  582. enum {
  583. OPT_Z = (1 << 0) * ENABLE_SELINUX,
  584. OPT_T = (1 << ENABLE_SELINUX) * ENABLE_FEATURE_SHOW_THREADS,
  585. OPT_l = (1 << ENABLE_SELINUX) * (1 << ENABLE_FEATURE_SHOW_THREADS) * ENABLE_FEATURE_PS_LONG,
  586. };
  587. #if ENABLE_FEATURE_PS_LONG
  588. time_t now = now; /* for compiler */
  589. unsigned long uptime = uptime;
  590. #endif
  591. /* If we support any options, parse argv */
  592. #if ENABLE_SELINUX || ENABLE_FEATURE_SHOW_THREADS || ENABLE_FEATURE_PS_WIDE || ENABLE_FEATURE_PS_LONG
  593. int opts = 0;
  594. # if ENABLE_FEATURE_PS_WIDE
  595. /* -w is a bit complicated */
  596. int w_count = 0;
  597. opt_complementary = "-:ww";
  598. opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l")
  599. "w", &w_count);
  600. /* if w is given once, GNU ps sets the width to 132,
  601. * if w is given more than once, it is "unlimited"
  602. */
  603. if (w_count) {
  604. terminal_width = (w_count == 1) ? 132 : MAX_WIDTH;
  605. } else {
  606. terminal_width = get_terminal_width(0);
  607. /* Go one less... */
  608. if (--terminal_width > MAX_WIDTH)
  609. terminal_width = MAX_WIDTH;
  610. }
  611. # else
  612. /* -w is not supported, only -Z and/or -T */
  613. opt_complementary = "-";
  614. opts = getopt32(argv, IF_SELINUX("Z")IF_FEATURE_SHOW_THREADS("T")IF_FEATURE_PS_LONG("l"));
  615. # endif
  616. # if ENABLE_SELINUX
  617. if ((opts & OPT_Z) && is_selinux_enabled()) {
  618. psscan_flags = PSSCAN_PID | PSSCAN_CONTEXT
  619. | PSSCAN_STATE | PSSCAN_COMM;
  620. puts(" PID CONTEXT STAT COMMAND");
  621. } else
  622. # endif
  623. if (opts & OPT_l) {
  624. psscan_flags = PSSCAN_STATE | PSSCAN_UIDGID | PSSCAN_PID | PSSCAN_PPID
  625. | PSSCAN_TTY | PSSCAN_STIME | PSSCAN_UTIME | PSSCAN_COMM
  626. | PSSCAN_VSZ | PSSCAN_RSS;
  627. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
  628. * mandates for -l:
  629. * -F Flags (?)
  630. * S State
  631. * UID,PID,PPID
  632. * -C CPU usage
  633. * -PRI The priority of the process; higher numbers mean lower priority
  634. * -NI Nice value
  635. * -ADDR The address of the process (?)
  636. * SZ The size in blocks of the core image
  637. * -WCHAN The event for which the process is waiting or sleeping
  638. * TTY
  639. * TIME The cumulative execution time
  640. * CMD
  641. * We don't show fields marked with '-'.
  642. * We show VSZ and RSS instead of SZ.
  643. * We also show STIME (standard says that -f shows it, -l doesn't).
  644. */
  645. puts("S UID PID PPID VSZ RSS TTY STIME TIME CMD");
  646. # if ENABLE_FEATURE_PS_LONG
  647. now = time(NULL);
  648. uptime = get_uptime();
  649. # endif
  650. }
  651. else {
  652. puts(" PID USER VSZ STAT COMMAND");
  653. }
  654. if (opts & OPT_T) {
  655. psscan_flags |= PSSCAN_TASKS;
  656. }
  657. #endif
  658. p = NULL;
  659. while ((p = procps_scan(p, psscan_flags)) != NULL) {
  660. int len;
  661. #if ENABLE_SELINUX
  662. if (psscan_flags & PSSCAN_CONTEXT) {
  663. len = printf("%5u %-32.32s %s ",
  664. p->pid,
  665. p->context ? p->context : "unknown",
  666. p->state);
  667. } else
  668. #endif
  669. {
  670. char buf6[6];
  671. smart_ulltoa5(p->vsz, buf6, " mgtpezy")[0] = '\0';
  672. #if ENABLE_FEATURE_PS_LONG
  673. if (opts & OPT_l) {
  674. char bufr[6], stime_str[6];
  675. char tty[2 * sizeof(int)*3 + 2];
  676. char *endp;
  677. unsigned sut = (p->stime + p->utime) / 100;
  678. unsigned elapsed = uptime - (p->start_time / 100);
  679. time_t start = now - elapsed;
  680. struct tm *tm = localtime(&start);
  681. smart_ulltoa5(p->rss, bufr, " mgtpezy")[0] = '\0';
  682. if (p->tty_major == 136)
  683. /* It should be pts/N, not ptsN, but N > 9
  684. * will overflow field width...
  685. */
  686. endp = stpcpy(tty, "pts");
  687. else
  688. if (p->tty_major == 4) {
  689. endp = stpcpy(tty, "tty");
  690. if (p->tty_minor >= 64) {
  691. p->tty_minor -= 64;
  692. *endp++ = 'S';
  693. }
  694. }
  695. else
  696. endp = tty + sprintf(tty, "%d:", p->tty_major);
  697. strcpy(endp, utoa(p->tty_minor));
  698. strftime(stime_str, 6, (elapsed >= (24 * 60 * 60)) ? "%b%d" : "%H:%M", tm);
  699. stime_str[5] = '\0';
  700. // S UID PID PPID VSZ RSS TTY STIME TIME CMD
  701. len = printf("%c %5u %5u %5u %5s %5s %-5s %s %02u:%02u:%02u ",
  702. p->state[0], p->uid, p->pid, p->ppid, buf6, bufr, tty,
  703. stime_str, sut / 3600, (sut % 3600) / 60, sut % 60);
  704. } else
  705. #endif
  706. {
  707. const char *user = get_cached_username(p->uid);
  708. len = printf("%5u %-8.8s %s %s ",
  709. p->pid, user, buf6, p->state);
  710. }
  711. }
  712. {
  713. int sz = terminal_width - len;
  714. if (sz >= 0) {
  715. char buf[sz + 1];
  716. read_cmdline(buf, sz, p->pid, p->comm);
  717. puts(buf);
  718. }
  719. }
  720. }
  721. if (ENABLE_FEATURE_CLEAN_UP)
  722. clear_username_cache();
  723. return EXIT_SUCCESS;
  724. }
  725. #endif /* !ENABLE_DESKTOP */