dtpstree.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. // DT PS Tree
  2. //
  3. // Douglas Thrift
  4. //
  5. // dtpstree.cpp
  6. /* Copyright 2010 Douglas Thrift
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #include <cerrno>
  21. #include <climits>
  22. #include <cstdarg>
  23. #include <cstdio>
  24. #include <cstdlib>
  25. #include <cstring>
  26. #include <iostream>
  27. #include <map>
  28. #include <set>
  29. #include <sstream>
  30. #include <string>
  31. #include <vector>
  32. #ifdef __GLIBC__
  33. #include <bsd/stdlib.h>
  34. #else
  35. #include <libgen.h>
  36. #endif
  37. #include <curses.h>
  38. #include <err.h>
  39. #include <fcntl.h>
  40. #include <getopt.h>
  41. #include <kvm.h>
  42. #include <paths.h>
  43. #include <pwd.h>
  44. #include <sys/param.h>
  45. #include <sys/sysctl.h>
  46. #include <sys/user.h>
  47. #include <term.h>
  48. #include <vis.h>
  49. #include "foreach.hpp"
  50. #define DTPSTREE_PROGRAM "dtpstree"
  51. #define DTPSTREE_VERSION "1.0.1"
  52. class Proc;
  53. typedef std::map<pid_t, Proc *> PidMap;
  54. typedef std::multimap<std::string, Proc *> NameMap;
  55. enum Flags
  56. {
  57. Arguments = 0x0001,
  58. Ascii = 0x0002,
  59. NoCompact = 0x0004,
  60. Highlight = 0x0008,
  61. Vt100 = 0x0010,
  62. ShowKernel = 0x0020,
  63. Long = 0x0040,
  64. NumericSort = 0x0080,
  65. ShowPids = 0x0100,
  66. ShowTitles = 0x0200,
  67. UidChanges = 0x0400,
  68. Unicode = 0x0800,
  69. Version = 0x1000,
  70. Pid = 0x2000,
  71. User = 0x4000
  72. };
  73. enum Escape { None, BoxDrawing, Bright };
  74. struct Segment
  75. {
  76. size_t width_;
  77. Escape escape_;
  78. char *string_;
  79. inline Segment(size_t width, Escape escape, char *string) : width_(width), escape_(escape), string_(string) {}
  80. };
  81. struct Branch
  82. {
  83. std::string indentation_;
  84. bool done_;
  85. inline Branch(size_t indentation) : indentation_(indentation, ' '), done_(false) {}
  86. };
  87. class Tree
  88. {
  89. const uint16_t &flags_;
  90. bool vt100_;
  91. wchar_t horizontal_, vertical_, upAndRight_, verticalAndRight_, downAndHorizontal_;
  92. size_t maxWidth_, width_;
  93. bool max_, suppress_;
  94. std::vector<Segment> segments_;
  95. std::vector<Branch> branches_;
  96. bool first_, last_;
  97. size_t duplicate_;
  98. public:
  99. Tree(const uint16_t &flags) : flags_(flags), vt100_(false), maxWidth_(0), width_(0), max_(false), suppress_(false), duplicate_(0)
  100. {
  101. bool tty(isatty(1));
  102. if (flags & Ascii)
  103. {
  104. ascii:
  105. horizontal_ = L'-';
  106. vertical_ = L'|';
  107. upAndRight_ = L'`';
  108. verticalAndRight_ = L'|';
  109. downAndHorizontal_ = L'+';
  110. }
  111. else if (flags & Unicode)
  112. {
  113. unicode:
  114. if (!std::setlocale(LC_CTYPE, ""))
  115. goto vt100;
  116. horizontal_ = L'\x2500';
  117. vertical_ = L'\x2502';
  118. upAndRight_ = L'\x2514';
  119. verticalAndRight_ = L'\x251c';
  120. downAndHorizontal_ = L'\x252c';
  121. char *test;
  122. if (asprintf(&test, "%lc%lc%lc%lc%lc", horizontal_, vertical_, upAndRight_, verticalAndRight_, downAndHorizontal_) == -1)
  123. goto vt100;
  124. std::free(test);
  125. }
  126. else if (flags & Vt100)
  127. {
  128. vt100:
  129. vt100_ = true;
  130. horizontal_ = L'\x71';
  131. vertical_ = L'\x78';
  132. upAndRight_ = L'\x6d';
  133. verticalAndRight_ = L'\x74';
  134. downAndHorizontal_ = L'\x77';
  135. }
  136. else if (tty)
  137. goto unicode;
  138. else
  139. goto ascii;
  140. if (!(flags & Long) && tty)
  141. {
  142. int code;
  143. if (setupterm(NULL, 1, &code) == OK)
  144. {
  145. maxWidth_ = tigetnum("cols");
  146. if (tigetflag("am") && !tigetflag("xenl"))
  147. suppress_ = true;
  148. }
  149. else
  150. maxWidth_ = 80;
  151. }
  152. }
  153. void print(const std::string &string, bool highlight, size_t duplicate)
  154. {
  155. Escape escape(vt100_ ? BoxDrawing : None);
  156. if (!first_ || flags_ & Arguments)
  157. {
  158. size_t last(branches_.size() - 1);
  159. _foreach (std::vector<Branch>, branch, branches_)
  160. {
  161. size_t width(branch->indentation_.size() + 2);
  162. if (_index == last)
  163. {
  164. wchar_t line;
  165. if (last_)
  166. {
  167. branch->done_ = true;
  168. line = upAndRight_;
  169. }
  170. else
  171. line = verticalAndRight_;
  172. print(width, escape, "%s%lc%lc", branch->indentation_.c_str(), line, horizontal_);
  173. }
  174. else
  175. print(width, escape, "%s%lc ", branch->indentation_.c_str(), branch->done_ ? ' ' : vertical_);
  176. }
  177. }
  178. else if (branches_.size())
  179. {
  180. wchar_t line;
  181. if (last_)
  182. {
  183. branches_.back().done_ = true;
  184. line = horizontal_;
  185. }
  186. else
  187. line = downAndHorizontal_;
  188. print(3, escape, "%lc%lc%lc", horizontal_, line, horizontal_);
  189. }
  190. size_t size(0);
  191. if (duplicate)
  192. {
  193. std::ostringstream string;
  194. string << duplicate << "*[";
  195. size = string.str().size();
  196. print(size, None, "%s", string.str().c_str());
  197. ++duplicate_;
  198. }
  199. print(string.size(), highlight ? Bright : None, "%s", string.c_str());
  200. branches_.push_back(Branch(!(flags_ & Arguments) ? size + string.size() + 1 : 2));
  201. }
  202. inline void printArg(const std::string &arg, bool last)
  203. {
  204. if (max_)
  205. return;
  206. size_t width(arg.size() + 1);
  207. width_ += width;
  208. char *string;
  209. if (maxWidth_ && !(flags_ & Long))
  210. if (width_ > maxWidth_ || !last && width_ + 3 >= maxWidth_)
  211. {
  212. width -= width_ - maxWidth_;
  213. width_ = maxWidth_;
  214. max_ = true;
  215. ssize_t size(static_cast<ssize_t>(width) - 4);
  216. asprintf(&string, " %s...", size > 0 ? arg.substr(0, size).c_str() : "");
  217. }
  218. else
  219. goto print;
  220. else
  221. print:
  222. asprintf(&string, " %s", arg.c_str());
  223. segments_.push_back(Segment(width, None, string));
  224. }
  225. inline void pop(bool children)
  226. {
  227. branches_.pop_back();
  228. if (!(flags_ & Arguments) && !children)
  229. done();
  230. }
  231. void done()
  232. {
  233. if (duplicate_)
  234. {
  235. print(duplicate_, None, "%s", std::string(duplicate_, ']').c_str());
  236. duplicate_ = 0;
  237. }
  238. size_t last(segments_.size() - 1);
  239. _foreach (std::vector<Segment>, segment, segments_)
  240. {
  241. const char *begin, *end;
  242. switch (segment->escape_)
  243. {
  244. case BoxDrawing:
  245. begin = !_index || (segment - 1)->escape_ != BoxDrawing ? "\033(0\017" : "";
  246. end = _index == last || (segment + 1)->escape_ != BoxDrawing ? "\033(B\017" : "";
  247. break;
  248. case Bright:
  249. begin = "\033[1m";
  250. end = "\033[22m";
  251. break;
  252. default:
  253. begin = end = ""; break;
  254. }
  255. std::printf("%s%s%s", begin, segment->string_, end);
  256. std::free(segment->string_);
  257. }
  258. segments_.clear();
  259. if (suppress_ && width_ == maxWidth_)
  260. std::fflush(stdout);
  261. else
  262. std::printf("\n");
  263. width_ = 0;
  264. max_ = false;
  265. }
  266. inline Tree &operator()(bool first, bool last)
  267. {
  268. first_ = first;
  269. last_ = last;
  270. return *this;
  271. }
  272. private:
  273. void print(size_t width, Escape escape, const char * format, ...)
  274. {
  275. if (max_)
  276. return;
  277. std::va_list args;
  278. va_start(args, format);
  279. char *string;
  280. vasprintf(&string, format, args);
  281. va_end(args);
  282. width_ += width;
  283. if (maxWidth_ && !(flags_ & Long))
  284. if (width_ > maxWidth_)
  285. {
  286. width -= width_ - maxWidth_;
  287. width_ = maxWidth_;
  288. max_ = true;
  289. bool previous = !width;
  290. if (previous)
  291. {
  292. std::free(string);
  293. const Segment &segment(segments_.back());
  294. width = segment.width_;
  295. string = segment.string_;
  296. }
  297. std::wstring wide(width - 1, '\0');
  298. std::mbstowcs(const_cast<wchar_t *>(wide.data()), string, wide.size());
  299. std::free(string);
  300. asprintf(&string, "%ls+", wide.c_str());
  301. if (previous)
  302. {
  303. segments_.back().string_ = string;
  304. return;
  305. }
  306. }
  307. segments_.push_back(Segment(width, escape, string));
  308. }
  309. };
  310. class Proc
  311. {
  312. const uint16_t &flags_;
  313. kvm_t *kd_;
  314. kinfo_proc *proc_;
  315. mutable std::string name_, print_;
  316. Proc *parent_;
  317. PidMap childrenByPid_;
  318. NameMap childrenByName_;
  319. bool highlight_, root_;
  320. int8_t compact_;
  321. size_t duplicate_;
  322. public:
  323. inline Proc(const uint16_t &flags, kvm_t *kd, kinfo_proc *proc) : flags_(flags), kd_(kd), proc_(proc), parent_(NULL), highlight_(false), root_(false), compact_(-1), duplicate_(0) {}
  324. inline const std::string &name() const
  325. {
  326. if (name_.empty())
  327. name_ = visual(proc_->ki_comm);
  328. return name_;
  329. }
  330. inline pid_t parent() const { return proc_->ki_ppid; }
  331. inline pid_t pid() const { return proc_->ki_pid; }
  332. inline void child(Proc *proc)
  333. {
  334. if (proc == this)
  335. return;
  336. proc->parent_ = this;
  337. childrenByPid_[proc->pid()] = proc;
  338. childrenByName_.insert(NameMap::value_type(proc->name(), proc));
  339. }
  340. inline void highlight()
  341. {
  342. highlight_ = true;
  343. if (parent_)
  344. parent_->highlight();
  345. }
  346. inline bool compact()
  347. {
  348. if (compact_ == -1)
  349. compact_ = compact(childrenByName_);
  350. return compact_;
  351. }
  352. bool root(uid_t uid)
  353. {
  354. if (flags_ & User)
  355. {
  356. if (uid == this->uid())
  357. {
  358. Proc *parent(parent_);
  359. while (parent)
  360. {
  361. if (parent->uid() == uid)
  362. return false;
  363. parent = parent->parent_;
  364. }
  365. return root_ = true;
  366. }
  367. return false;
  368. }
  369. return root_ = !parent_;
  370. }
  371. void printByPid(Tree &tree) const
  372. {
  373. if (duplicate_ == 1)
  374. return;
  375. print(tree);
  376. size_t last(childrenByPid_.size() - 1);
  377. _foreach (const PidMap, child, childrenByPid_)
  378. child->second->printByPid(tree(!_index, _index == last));
  379. tree.pop(children());
  380. }
  381. void printByName(Tree &tree) const
  382. {
  383. if (duplicate_ == 1)
  384. return;
  385. print(tree);
  386. size_t last(childrenByName_.size() - 1);
  387. _foreach (const NameMap, child, childrenByName_)
  388. child->second->printByName(tree(!_index, _index == last));
  389. tree.pop(children());
  390. }
  391. static bool compact(NameMap &names)
  392. {
  393. Proc *previous(NULL);
  394. bool compact(true);
  395. _foreach (NameMap, name, names)
  396. {
  397. Proc *proc(name->second);
  398. if (proc->duplicate_)
  399. continue;
  400. size_t duplicate(proc->compact());
  401. if (compact && duplicate && (!previous || proc->print() == previous->print()))
  402. previous = proc;
  403. else
  404. compact = false;
  405. size_t count(names.count(name->first));
  406. if (!duplicate || count == 1)
  407. continue;
  408. _forall(NameMap::iterator, n4me, (++name)--, names.upper_bound(name->first))
  409. {
  410. Proc *pr0c(n4me->second);
  411. if (true)
  412. duplicate += ++pr0c->duplicate_;
  413. }
  414. if (duplicate != 1)
  415. proc->duplicate_ = duplicate;
  416. }
  417. return compact;
  418. }
  419. private:
  420. inline std::string visual(const char *string) const
  421. {
  422. std::string visual(std::strlen(string) * 4 + 1, '\0');
  423. visual.resize(strvis(const_cast<char *>(visual.data()), string, VIS_TAB | VIS_NL | VIS_NOSLASH));
  424. return visual;
  425. }
  426. void print(Tree &tree) const
  427. {
  428. tree.print(print(), highlight_, duplicate_);
  429. if (flags_ & Arguments)
  430. {
  431. char **argv(kvm_getargv(kd_, proc_, 0));
  432. if (argv && *argv)
  433. for (++argv; *argv; ++argv)
  434. tree.printArg(visual(*argv), !*(argv + 1));
  435. tree.done();
  436. }
  437. }
  438. const std::string &print() const
  439. {
  440. if (print_.empty())
  441. {
  442. std::ostringstream print;
  443. if (flags_ & ShowTitles)
  444. {
  445. char **argv(kvm_getargv(kd_, proc_, 0));
  446. if (argv)
  447. print << visual(*argv);
  448. else
  449. print << name();
  450. }
  451. else
  452. print << name();
  453. bool p1d(flags_ & ShowPids), args(flags_ & Arguments);
  454. bool change(flags_ & UidChanges && (root_ ? !(flags_ & User) && uid() : parent_ && uid() != parent_->uid()));
  455. bool parens((p1d || change) && !args);
  456. if (parens)
  457. print << '(';
  458. if (p1d)
  459. {
  460. if (!parens)
  461. print << ',';
  462. print << pid();
  463. }
  464. if (change)
  465. {
  466. if (!parens || p1d)
  467. print << ',';
  468. passwd *user(getpwuid(uid()));
  469. print << user->pw_name;
  470. }
  471. if (parens)
  472. print << ')';
  473. print_ = print.str();
  474. }
  475. return print_;
  476. }
  477. inline bool children() const { return childrenByName_.size(); }
  478. inline uid_t uid() const { return proc_->ki_ruid; }
  479. };
  480. static void help(const char *program, option options[], int code = 0)
  481. {
  482. std::printf("Usage: %s [options] [PID|USER]\n\nOptions:\n", basename(program));
  483. for (option *option(options); option->name; ++option)
  484. {
  485. std::string name(option->name);
  486. std::ostringstream arguments;
  487. switch (option->val)
  488. {
  489. case 'H':
  490. if (name != "highlight")
  491. continue;
  492. arguments << "-H[PID], --highlight[=PID]"; break;
  493. case 0:
  494. if (name == "pid")
  495. arguments << "PID, --pid=PID";
  496. else if (name == "user")
  497. arguments << "USER, --user=USER";
  498. else
  499. goto argument;
  500. break;
  501. case 'c':
  502. if (name != "no-compact")
  503. continue;
  504. default:
  505. arguments << '-' << static_cast<char>(option->val) << ", ";
  506. argument:
  507. arguments << "--" << name;
  508. }
  509. const char *description("");
  510. switch (option->val)
  511. {
  512. case 'a':
  513. description = "show command line arguments"; break;
  514. case 'A':
  515. description = "use ASCII line drawing characters"; break;
  516. case 'c':
  517. description = "don't compact identical subtrees"; break;
  518. case 'h':
  519. description = "show this help message and exit"; break;
  520. case 'H':
  521. description = "highlight the current process (or PID) and its\n ancestors"; break;
  522. case 'G':
  523. description = "use VT100 line drawing characters"; break;
  524. case 'k':
  525. description = "show kernel processes"; break;
  526. case 'l':
  527. description = "don't truncate long lines"; break;
  528. case 'n':
  529. description = "sort output by PID"; break;
  530. case 'p':
  531. description = "show PIDs; implies -c"; break;
  532. case 't':
  533. description = "show process titles"; break;
  534. case 'u':
  535. description = "show uid transitions"; break;
  536. case 'U':
  537. description = "use Unicode line drawing characters"; break;
  538. case 'V':
  539. description = "show version information and exit"; break;
  540. case 0:
  541. if (name == "pid")
  542. description = "show only the tree rooted at the process PID";
  543. else if (name == "user")
  544. description = "show only trees rooted at processes of USER";
  545. }
  546. std::printf(" %-27s %s\n", arguments.str().c_str(), description);
  547. }
  548. std::exit(code);
  549. }
  550. template <typename Type, long long minimum, long long maximum>
  551. static Type value(char *program, option options[], bool *success = NULL)
  552. {
  553. const char *error;
  554. long long value(strtonum(optarg, minimum, maximum, &error));
  555. if (error)
  556. if (success && errno == EINVAL)
  557. *success = false;
  558. else
  559. {
  560. warnx("Number is %s: \"%s\"", error, optarg);
  561. help(program, options, 1);
  562. }
  563. else if (success)
  564. *success = true;
  565. return value;
  566. }
  567. static uint16_t options(int argc, char *argv[], pid_t &hpid, pid_t &pid, char *&user)
  568. {
  569. option options[] = {
  570. { "arguments", no_argument, NULL, 'a' },
  571. { "ascii", no_argument, NULL, 'A' },
  572. { "compact", no_argument, NULL, 'c' },
  573. { "no-compact", no_argument, NULL, 'c' },
  574. { "help", no_argument, NULL, 'h' },
  575. { "highlight", optional_argument, NULL, 'H' },
  576. { "highlight-all", no_argument, NULL, 'H' },
  577. { "highlight-pid", required_argument, NULL, 'H' },
  578. { "vt100", no_argument, NULL, 'G' },
  579. { "show-kernel", no_argument, NULL, 'k' },
  580. { "long", no_argument, NULL, 'l' },
  581. { "numeric-sort", no_argument, NULL, 'n' },
  582. { "show-pids", no_argument, NULL, 'p' },
  583. { "show-titles", no_argument, NULL, 't' },
  584. { "uid-changes", no_argument, NULL, 'u' },
  585. { "unicode", no_argument, NULL, 'U' },
  586. { "version", no_argument, NULL, 'V' },
  587. { "pid", required_argument, NULL, 0 },
  588. { "user", required_argument, NULL, 0 },
  589. { NULL, 0, NULL, 0 }
  590. };
  591. int option, index;
  592. uint16_t flags(0);
  593. char *program(argv[0]);
  594. while ((option = getopt_long(argc, argv, "aAchH::GklnptuUV", options, &index)) != -1)
  595. switch (option)
  596. {
  597. case 'a':
  598. flags |= Arguments | NoCompact; break;
  599. case 'A':
  600. flags |= Ascii;
  601. flags &= ~Vt100;
  602. flags &= ~Unicode;
  603. break;
  604. case 'c':
  605. flags |= NoCompact; break;
  606. case 'h':
  607. help(program, options);
  608. case 'H':
  609. hpid = optarg ? value<pid_t, 0, INT_MAX>(program, options) : getpid();
  610. flags |= Highlight;
  611. break;
  612. case 'G':
  613. flags |= Vt100;
  614. flags &= ~Ascii;
  615. flags &= ~Unicode;
  616. break;
  617. case 'k':
  618. flags |= ShowKernel; break;
  619. case 'l':
  620. flags |= Long; break;
  621. case 'n':
  622. flags |= NumericSort; break;
  623. case 'p':
  624. flags |= NoCompact | ShowPids; break;
  625. case 't':
  626. flags |= ShowTitles; break;
  627. case 'u':
  628. flags |= UidChanges; break;
  629. case 'U':
  630. flags |= Unicode;
  631. flags &= ~Ascii;
  632. flags &= ~Vt100;
  633. break;
  634. case 'V':
  635. flags |= Version; break;
  636. case 0:
  637. {
  638. std::string option(options[index].name);
  639. if (option == "pid")
  640. {
  641. pid = value<pid_t, 0, INT_MAX>(program, options);
  642. flags |= Pid;
  643. flags &= ~User;
  644. }
  645. else if (option == "user")
  646. {
  647. std::free(user);
  648. user = strdup(optarg);
  649. flags |= User;
  650. flags &= ~Pid;
  651. }
  652. }
  653. break;
  654. case '?':
  655. help(program, options, 1);
  656. }
  657. _forall (int, index, optind, argc)
  658. {
  659. bool success;
  660. optarg = argv[index];
  661. pid = value<pid_t, 0, INT_MAX>(program, options, &success);
  662. if (success)
  663. {
  664. flags |= Pid;
  665. flags &= ~User;
  666. }
  667. else
  668. {
  669. std::free(user);
  670. user = strdup(optarg);
  671. flags |= User;
  672. flags &= ~Pid;
  673. }
  674. }
  675. return flags;
  676. }
  677. int main(int argc, char *argv[])
  678. {
  679. pid_t hpid(0), pid(0);
  680. char *user(NULL);
  681. uint16_t flags(options(argc, argv, hpid, pid, user));
  682. if (flags & Version)
  683. {
  684. std::printf(DTPSTREE_PROGRAM " " DTPSTREE_VERSION "\n");
  685. return 0;
  686. }
  687. uid_t uid(0);
  688. if (flags & User)
  689. {
  690. errno = 0;
  691. passwd *us3r(getpwnam(user));
  692. if (!us3r)
  693. errno ? err(1, NULL) : errx(1, "Unknown user: \"%s\"", user);
  694. uid = us3r->pw_uid;
  695. }
  696. char error[_POSIX2_LINE_MAX];
  697. kvm_t *kd(kvm_openfiles(NULL, _PATH_DEVNULL, NULL, O_RDONLY, error));
  698. if (!kd)
  699. errx(1, "%s", error);
  700. typedef kinfo_proc *InfoProc;
  701. int count;
  702. InfoProc procs(kvm_getprocs(kd, KERN_PROC_PROC, 0, &count));
  703. if (!procs)
  704. errx(1, "%s", kvm_geterr(kd));
  705. PidMap pids;
  706. _forall (InfoProc, proc, procs, procs + count)
  707. if (flags & ShowKernel || proc->ki_ppid != 0 || proc->ki_pid == 1)
  708. pids[proc->ki_pid] = new Proc(flags, kd, proc);
  709. enum { PidSort, NameSort } sort(flags & NumericSort ? PidSort : NameSort);
  710. _foreach (PidMap, pid, pids)
  711. {
  712. Proc *proc(pid->second);
  713. PidMap::iterator parent(pids.find(proc->parent()));
  714. if (parent != pids.end())
  715. parent->second->child(proc);
  716. }
  717. if (flags & Highlight)
  718. {
  719. PidMap::iterator pid(pids.find(hpid));
  720. if (pid != pids.end())
  721. pid->second->highlight();
  722. }
  723. Tree tree(flags);
  724. if (flags & Pid)
  725. {
  726. PidMap::iterator p1d(pids.find(pid));
  727. if (p1d != pids.end())
  728. {
  729. Proc *proc(p1d->second);
  730. if (!(flags & NoCompact))
  731. proc->compact();
  732. switch (sort)
  733. {
  734. case PidSort:
  735. proc->printByPid(tree);
  736. break;
  737. case NameSort:
  738. proc->printByName(tree);
  739. }
  740. }
  741. }
  742. else
  743. {
  744. NameMap names;
  745. _foreach (PidMap, pid, pids)
  746. {
  747. Proc *proc(pid->second);
  748. if (proc->root(uid))
  749. names.insert(NameMap::value_type(proc->name(), proc));
  750. }
  751. if (!(flags & NoCompact))
  752. Proc::compact(names);
  753. switch (sort)
  754. {
  755. case PidSort:
  756. _foreach (PidMap, pid, pids)
  757. {
  758. Proc *proc(pid->second);
  759. if (proc->root(uid))
  760. proc->printByPid(tree);
  761. }
  762. break;
  763. case NameSort:
  764. _foreach (NameMap, name, names)
  765. name->second->printByName(tree);
  766. }
  767. }
  768. _foreach (PidMap, pid, pids)
  769. delete pid->second;
  770. return 0;
  771. }
  772. // display a tree of processes