ps.c 21 KB

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