start-stop-daemon.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. /*
  2. * A rewrite of the original Debian's start-stop-daemon Perl script
  3. * in C (faster - it is executed many times during system startup).
  4. *
  5. * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
  6. * public domain. Based conceptually on start-stop-daemon.pl, by Ian
  7. * Jackson <ijackson@gnu.ai.mit.edu>. May be used and distributed
  8. * freely for any purpose. Changes by Christian Schwarz
  9. * <schwarz@monet.m.isar.de>, to make output conform to the Debian
  10. * Console Message Standard, also placed in public domain. Minor
  11. * changes by Klee Dienes <klee@debian.org>, also placed in the Public
  12. * Domain.
  13. *
  14. * Changes by Ben Collins <bcollins@debian.org>, added --chuid, --background
  15. * and --make-pidfile options, placed in public domain aswell.
  16. *
  17. * Port to OpenBSD by Sontri Tomo Huynh <huynh.29@osu.edu>
  18. * and Andreas Schuldei <andreas@schuldei.org>
  19. *
  20. * Changes by Ian Jackson: added --retry (and associated rearrangements).
  21. */
  22. #include "config.h"
  23. #if defined(linux) || (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
  24. # define OSLinux
  25. #elif defined(__GNU__)
  26. # define OSHURD
  27. #elif defined(__sparc__)
  28. # define OSsunos
  29. #elif defined(OPENBSD) || defined(__OpenBSD__)
  30. # define OSOpenBSD
  31. #elif defined(hpux)
  32. # define OShpux
  33. #elif defined(__FreeBSD__)
  34. # define OSFreeBSD
  35. #elif defined(__NetBSD__)
  36. # define OSNetBSD
  37. #else
  38. # error Unknown architecture - cannot build start-stop-daemon
  39. #endif
  40. #define MIN_POLL_INTERVAL 20000 /*us*/
  41. #if defined(OSHURD)
  42. # include <hurd.h>
  43. # include <ps.h>
  44. #endif
  45. #if defined(OSOpenBSD) || defined(OSFreeBSD) || defined(OSNetBSD)
  46. #include <sys/param.h>
  47. #include <sys/proc.h>
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <err.h>
  51. #include <limits.h>
  52. #endif
  53. #ifdef HAVE_KVM_H
  54. #include <kvm.h>
  55. #include <sys/sysctl.h>
  56. #include <sys/user.h>
  57. #endif
  58. #if defined(OShpux)
  59. #include <sys/param.h>
  60. #include <sys/pstat.h>
  61. #endif
  62. #include <errno.h>
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include <stdarg.h>
  67. #include <signal.h>
  68. #include <sys/stat.h>
  69. #include <dirent.h>
  70. #include <sys/time.h>
  71. #include <unistd.h>
  72. #include <getopt.h>
  73. #include <pwd.h>
  74. #include <grp.h>
  75. #include <sys/ioctl.h>
  76. #include <sys/types.h>
  77. #include <sys/termios.h>
  78. #include <fcntl.h>
  79. #include <limits.h>
  80. #include <assert.h>
  81. #include <ctype.h>
  82. #ifdef HAVE_SYS_CDEFS_H
  83. #include <sys/cdefs.h>
  84. #endif
  85. #ifdef HAVE_STDDEF_H
  86. #include <stddef.h>
  87. #endif
  88. #ifdef HAVE_ERROR_H
  89. # include <error.h>
  90. #endif
  91. #if HAVE_C_ATTRIBUTE
  92. # define CONSTANT __attribute__((constant))
  93. # define PRINTFFORMAT(si, tc) __attribute__((format(printf,si,tc)))
  94. # define NONRETURNING __attribute__((noreturn))
  95. # define UNUSED __attribute__((unused))
  96. # define NONRETURNPRINTFFORMAT(si, tc) __attribute__((format(printf,si,tc),noreturn))
  97. #else
  98. # define CONSTANT
  99. # define PRINTFFORMAT(si, tc)
  100. # define NONRETURNING
  101. # define UNUSED
  102. # define NONRETURNPRINTFFORMAT(si, tc)
  103. #endif
  104. static int testmode = 0;
  105. static int quietmode = 0;
  106. static int exitnodo = 1;
  107. static int start = 0;
  108. static int stop = 0;
  109. static int background = 0;
  110. static int mpidfile = 0;
  111. static int signal_nr = 15;
  112. static int user_id = -1;
  113. static int runas_uid = -1;
  114. static int runas_gid = -1;
  115. static const char *userspec = NULL;
  116. static char *changeuser = NULL;
  117. static const char *changegroup = NULL;
  118. static char *changeroot = NULL;
  119. static const char *changedir = "/";
  120. static const char *cmdname = NULL;
  121. static char *execname = NULL;
  122. static char *startas = NULL;
  123. static const char *pidfile = NULL;
  124. static char what_stop[1024];
  125. static const char *progname = "";
  126. static int nicelevel = 0;
  127. static int umask_value = -1;
  128. static struct stat exec_stat;
  129. #if defined(OSHURD)
  130. static struct proc_stat_list *procset = NULL;
  131. #endif
  132. struct pid_list {
  133. struct pid_list *next;
  134. pid_t pid;
  135. };
  136. static struct pid_list *found = NULL;
  137. static struct pid_list *killed = NULL;
  138. struct schedule_item {
  139. enum { sched_timeout, sched_signal, sched_goto, sched_forever } type;
  140. int value; /* seconds, signal no., or index into array */
  141. /* sched_forever is only seen within parse_schedule and callees */
  142. };
  143. static int schedule_length;
  144. static struct schedule_item *schedule = NULL;
  145. static void *xmalloc(int size);
  146. static void push(struct pid_list **list, pid_t pid);
  147. static void do_help(void);
  148. static void parse_options(int argc, char * const *argv);
  149. static int pid_is_user(pid_t pid, uid_t uid);
  150. static int pid_is_cmd(pid_t pid, const char *name);
  151. static void check(pid_t pid);
  152. static void do_pidfile(const char *name);
  153. static void do_stop(int signal_nr, int quietmode,
  154. int *n_killed, int *n_notkilled, int retry_nr);
  155. #if defined(OSLinux) || defined(OShpux)
  156. static int pid_is_exec(pid_t pid, const struct stat *esb);
  157. #endif
  158. #ifdef __GNUC__
  159. static void fatal(const char *format, ...)
  160. NONRETURNPRINTFFORMAT(1, 2);
  161. static void badusage(const char *msg)
  162. NONRETURNING;
  163. #else
  164. static void fatal(const char *format, ...);
  165. static void badusage(const char *msg);
  166. #endif
  167. /* This next part serves only to construct the TVCALC macro, which
  168. * is used for doing arithmetic on struct timeval's. It works like this:
  169. * TVCALC(result, expression);
  170. * where result is a struct timeval (and must be an lvalue) and
  171. * expression is the single expression for both components. In this
  172. * expression you can use the special values TVELEM, which when fed a
  173. * const struct timeval* gives you the relevant component, and
  174. * TVADJUST. TVADJUST is necessary when subtracting timevals, to make
  175. * it easier to renormalise. Whenver you subtract timeval elements,
  176. * you must make sure that TVADJUST is added to the result of the
  177. * subtraction (before any resulting multiplication or what have you).
  178. * TVELEM must be linear in TVADJUST.
  179. */
  180. typedef long tvselector(const struct timeval*);
  181. static long tvselector_sec(const struct timeval *tv) { return tv->tv_sec; }
  182. static long tvselector_usec(const struct timeval *tv) { return tv->tv_usec; }
  183. #define TVCALC_ELEM(result, expr, sec, adj) \
  184. { \
  185. const long TVADJUST = adj; \
  186. long (*const TVELEM)(const struct timeval*) = tvselector_##sec; \
  187. (result).tv_##sec = (expr); \
  188. }
  189. #define TVCALC(result,expr) \
  190. do { \
  191. TVCALC_ELEM(result, expr, sec, (-1)); \
  192. TVCALC_ELEM(result, expr, usec, (+1000000)); \
  193. (result).tv_sec += (result).tv_usec / 1000000; \
  194. (result).tv_usec %= 1000000; \
  195. } while(0)
  196. static void
  197. fatal(const char *format, ...)
  198. {
  199. va_list arglist;
  200. fprintf(stderr, "%s: ", progname);
  201. va_start(arglist, format);
  202. vfprintf(stderr, format, arglist);
  203. va_end(arglist);
  204. fprintf(stderr, " (%s)\n", strerror (errno));
  205. exit(2);
  206. }
  207. static void *
  208. xmalloc(int size)
  209. {
  210. void *ptr;
  211. ptr = malloc(size);
  212. if (ptr)
  213. return ptr;
  214. fatal("malloc(%d) failed", size);
  215. }
  216. static void
  217. xgettimeofday(struct timeval *tv)
  218. {
  219. if (gettimeofday(tv,0) != 0)
  220. fatal("gettimeofday failed: %s", strerror(errno));
  221. }
  222. static void
  223. push(struct pid_list **list, pid_t pid)
  224. {
  225. struct pid_list *p;
  226. p = xmalloc(sizeof(*p));
  227. p->next = *list;
  228. p->pid = pid;
  229. *list = p;
  230. }
  231. static void
  232. clear(struct pid_list **list)
  233. {
  234. struct pid_list *here, *next;
  235. for (here = *list; here != NULL; here = next) {
  236. next = here->next;
  237. free(here);
  238. }
  239. *list = NULL;
  240. }
  241. static void
  242. do_help(void)
  243. {
  244. printf(
  245. "start-stop-daemon %s for Debian - small and fast C version written by\n"
  246. "Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>, public domain.\n"
  247. "\n"
  248. "Usage: start-stop-daemon [<option> ...] <command>\n"
  249. "\n"
  250. "Commands:\n"
  251. " -S|--start -- <argument> ... start a program and pass <arguments> to it\n"
  252. " -K|--stop stop a program\n"
  253. " -H|--help print help information\n"
  254. " -V|--version print version\n"
  255. "\n"
  256. "Options (at least one of --exec|--pidfile|--user is required):\n"
  257. " -x|--exec <executable> program to start/check if it is running\n"
  258. " -p|--pidfile <pid-file> pid file to check\n"
  259. " -c|--chuid <name|uid[:group|gid]>\n"
  260. " change to this user/group before starting\n"
  261. " process\n"
  262. " -u|--user <username>|<uid> stop processes owned by this user\n"
  263. " -g|--group <group|gid> run process as this group\n"
  264. " -n|--name <process-name> stop processes with this name\n"
  265. " -s|--signal <signal> signal to send (default TERM)\n"
  266. " -a|--startas <pathname> program to start (default is <executable>)\n"
  267. " -r|--chroot <directory> chroot to <directory> before starting\n"
  268. " -d|--chdir <directory> change to <directory> (default is /)\n"
  269. " -N|--nicelevel <incr> add incr to the process's nice level\n"
  270. " -k|--umask <mask> change the umask to <mask> before starting\n"
  271. " -b|--background force the process to detach\n"
  272. " -m|--make-pidfile create the pidfile before starting\n"
  273. " -R|--retry <schedule> check whether processes die, and retry\n"
  274. " -t|--test test mode, don't do anything\n"
  275. " -o|--oknodo exit status 0 (not 1) if nothing done\n"
  276. " -q|--quiet be more quiet\n"
  277. " -v|--verbose be more verbose\n"
  278. "\n"
  279. "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
  280. " -<signal-num>|[-]<signal-name> send that signal\n"
  281. " <timeout> wait that many seconds\n"
  282. " forever repeat remainder forever\n"
  283. "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
  284. "\n"
  285. "Exit status: 0 = done 1 = nothing done (=> 0 if --oknodo)\n"
  286. " 3 = trouble 2 = with --retry, processes wouldn't die\n",
  287. VERSION);
  288. }
  289. static void
  290. badusage(const char *msg)
  291. {
  292. if (msg)
  293. fprintf(stderr, "%s: %s\n", progname, msg);
  294. fprintf(stderr, "Try `%s --help' for more information.\n", progname);
  295. exit(3);
  296. }
  297. struct sigpair {
  298. const char *name;
  299. int signal;
  300. };
  301. const struct sigpair siglist[] = {
  302. { "ABRT", SIGABRT },
  303. { "ALRM", SIGALRM },
  304. { "FPE", SIGFPE },
  305. { "HUP", SIGHUP },
  306. { "ILL", SIGILL },
  307. { "INT", SIGINT },
  308. { "KILL", SIGKILL },
  309. { "PIPE", SIGPIPE },
  310. { "QUIT", SIGQUIT },
  311. { "SEGV", SIGSEGV },
  312. { "TERM", SIGTERM },
  313. { "USR1", SIGUSR1 },
  314. { "USR2", SIGUSR2 },
  315. { "CHLD", SIGCHLD },
  316. { "CONT", SIGCONT },
  317. { "STOP", SIGSTOP },
  318. { "TSTP", SIGTSTP },
  319. { "TTIN", SIGTTIN },
  320. { "TTOU", SIGTTOU }
  321. };
  322. static int parse_integer(const char *string, int *value_r) {
  323. unsigned long ul;
  324. char *ep;
  325. if (!string[0])
  326. return -1;
  327. ul= strtoul(string,&ep,10);
  328. if (ul > INT_MAX || *ep != '\0')
  329. return -1;
  330. *value_r= ul;
  331. return 0;
  332. }
  333. static int parse_signal(const char *signal_str, int *signal_nr)
  334. {
  335. unsigned int i;
  336. if (parse_integer(signal_str, signal_nr) == 0)
  337. return 0;
  338. for (i = 0; i < sizeof (siglist) / sizeof (siglist[0]); i++) {
  339. if (strcmp (signal_str, siglist[i].name) == 0) {
  340. *signal_nr = siglist[i].signal;
  341. return 0;
  342. }
  343. }
  344. return -1;
  345. }
  346. static int
  347. parse_umask(const char *string, int *value_r)
  348. {
  349. if (!string[0])
  350. return -1;
  351. errno = 0;
  352. *value_r = strtoul(string, NULL, 0);
  353. if (errno)
  354. return -1;
  355. else
  356. return 0;
  357. }
  358. static void
  359. parse_schedule_item(const char *string, struct schedule_item *item) {
  360. const char *after_hyph;
  361. if (!strcmp(string,"forever")) {
  362. item->type = sched_forever;
  363. } else if (isdigit(string[0])) {
  364. item->type = sched_timeout;
  365. if (parse_integer(string, &item->value) != 0)
  366. badusage("invalid timeout value in schedule");
  367. } else if ((after_hyph = string + (string[0] == '-')) &&
  368. parse_signal(after_hyph, &item->value) == 0) {
  369. item->type = sched_signal;
  370. } else {
  371. badusage("invalid schedule item (must be [-]<signal-name>, "
  372. "-<signal-number>, <timeout> or `forever'");
  373. }
  374. }
  375. static void
  376. parse_schedule(const char *schedule_str) {
  377. char item_buf[20];
  378. const char *slash;
  379. int count, repeatat;
  380. ptrdiff_t str_len;
  381. count = 0;
  382. for (slash = schedule_str; *slash; slash++)
  383. if (*slash == '/')
  384. count++;
  385. schedule_length = (count == 0) ? 4 : count+1;
  386. schedule = xmalloc(sizeof(*schedule) * schedule_length);
  387. if (count == 0) {
  388. schedule[0].type = sched_signal;
  389. schedule[0].value = signal_nr;
  390. parse_schedule_item(schedule_str, &schedule[1]);
  391. if (schedule[1].type != sched_timeout) {
  392. badusage ("--retry takes timeout, or schedule list"
  393. " of at least two items");
  394. }
  395. schedule[2].type = sched_signal;
  396. schedule[2].value = SIGKILL;
  397. schedule[3]= schedule[1];
  398. } else {
  399. count = 0;
  400. repeatat = -1;
  401. while (schedule_str != NULL) {
  402. slash = strchr(schedule_str,'/');
  403. str_len = slash ? slash - schedule_str : strlen(schedule_str);
  404. if (str_len >= (ptrdiff_t)sizeof(item_buf))
  405. badusage("invalid schedule item: far too long"
  406. " (you must delimit items with slashes)");
  407. memcpy(item_buf, schedule_str, str_len);
  408. item_buf[str_len] = 0;
  409. schedule_str = slash ? slash+1 : NULL;
  410. parse_schedule_item(item_buf, &schedule[count]);
  411. if (schedule[count].type == sched_forever) {
  412. if (repeatat >= 0)
  413. badusage("invalid schedule: `forever'"
  414. " appears more than once");
  415. repeatat = count;
  416. continue;
  417. }
  418. count++;
  419. }
  420. if (repeatat >= 0) {
  421. schedule[count].type = sched_goto;
  422. schedule[count].value = repeatat;
  423. count++;
  424. }
  425. assert(count == schedule_length);
  426. }
  427. }
  428. static void
  429. parse_options(int argc, char * const *argv)
  430. {
  431. static struct option longopts[] = {
  432. { "help", 0, NULL, 'H'},
  433. { "stop", 0, NULL, 'K'},
  434. { "start", 0, NULL, 'S'},
  435. { "version", 0, NULL, 'V'},
  436. { "startas", 1, NULL, 'a'},
  437. { "name", 1, NULL, 'n'},
  438. { "oknodo", 0, NULL, 'o'},
  439. { "pidfile", 1, NULL, 'p'},
  440. { "quiet", 0, NULL, 'q'},
  441. { "signal", 1, NULL, 's'},
  442. { "test", 0, NULL, 't'},
  443. { "user", 1, NULL, 'u'},
  444. { "group", 1, NULL, 'g'},
  445. { "chroot", 1, NULL, 'r'},
  446. { "verbose", 0, NULL, 'v'},
  447. { "exec", 1, NULL, 'x'},
  448. { "chuid", 1, NULL, 'c'},
  449. { "nicelevel", 1, NULL, 'N'},
  450. { "umask", 1, NULL, 'k'},
  451. { "background", 0, NULL, 'b'},
  452. { "make-pidfile", 0, NULL, 'm'},
  453. { "retry", 1, NULL, 'R'},
  454. { "chdir", 1, NULL, 'd'},
  455. { NULL, 0, NULL, 0}
  456. };
  457. const char *umask_str = NULL;
  458. const char *signal_str = NULL;
  459. const char *schedule_str = NULL;
  460. int c;
  461. for (;;) {
  462. c = getopt_long(argc, argv, "HKSVa:n:op:qr:s:tu:vx:c:N:k:bmR:g:d:",
  463. longopts, (int *) 0);
  464. if (c == -1)
  465. break;
  466. switch (c) {
  467. case 'H': /* --help */
  468. do_help();
  469. exit(0);
  470. case 'K': /* --stop */
  471. stop = 1;
  472. break;
  473. case 'S': /* --start */
  474. start = 1;
  475. break;
  476. case 'V': /* --version */
  477. printf("start-stop-daemon " VERSION "\n");
  478. exit(0);
  479. case 'a': /* --startas <pathname> */
  480. startas = optarg;
  481. break;
  482. case 'n': /* --name <process-name> */
  483. cmdname = optarg;
  484. break;
  485. case 'o': /* --oknodo */
  486. exitnodo = 0;
  487. break;
  488. case 'p': /* --pidfile <pid-file> */
  489. pidfile = optarg;
  490. break;
  491. case 'q': /* --quiet */
  492. quietmode = 1;
  493. break;
  494. case 's': /* --signal <signal> */
  495. signal_str = optarg;
  496. break;
  497. case 't': /* --test */
  498. testmode = 1;
  499. break;
  500. case 'u': /* --user <username>|<uid> */
  501. userspec = optarg;
  502. break;
  503. case 'v': /* --verbose */
  504. quietmode = -1;
  505. break;
  506. case 'x': /* --exec <executable> */
  507. execname = optarg;
  508. break;
  509. case 'c': /* --chuid <username>|<uid> */
  510. /* we copy the string just in case we need the
  511. * argument later. */
  512. changeuser = strdup(optarg);
  513. changeuser = strtok(changeuser, ":");
  514. changegroup = strtok(NULL, ":");
  515. break;
  516. case 'g': /* --group <group>|<gid> */
  517. changegroup = optarg;
  518. break;
  519. case 'r': /* --chroot /new/root */
  520. changeroot = optarg;
  521. break;
  522. case 'N': /* --nice */
  523. nicelevel = atoi(optarg);
  524. break;
  525. case 'k': /* --umask <mask> */
  526. umask_str = optarg;
  527. break;
  528. case 'b': /* --background */
  529. background = 1;
  530. break;
  531. case 'm': /* --make-pidfile */
  532. mpidfile = 1;
  533. break;
  534. case 'R': /* --retry <schedule>|<timeout> */
  535. schedule_str = optarg;
  536. break;
  537. case 'd': /* --chdir /new/dir */
  538. changedir = optarg;
  539. break;
  540. default:
  541. badusage(NULL); /* message printed by getopt */
  542. }
  543. }
  544. if (signal_str != NULL) {
  545. if (parse_signal (signal_str, &signal_nr) != 0)
  546. badusage("signal value must be numeric or name"
  547. " of signal (KILL, INT, ...)");
  548. }
  549. if (schedule_str != NULL) {
  550. parse_schedule(schedule_str);
  551. }
  552. if (umask_str != NULL) {
  553. if (parse_umask(umask_str, &umask_value) != 0)
  554. badusage("umask value must be a positive number");
  555. }
  556. if (start == stop)
  557. badusage("need one of --start or --stop");
  558. if (!execname && !pidfile && !userspec && !cmdname)
  559. badusage("need at least one of --exec, --pidfile, --user or --name");
  560. if (!startas)
  561. startas = execname;
  562. if (start && !startas)
  563. badusage("--start needs --exec or --startas");
  564. if (mpidfile && pidfile == NULL)
  565. badusage("--make-pidfile is only relevant with --pidfile");
  566. if (background && !start)
  567. badusage("--background is only relevant with --start");
  568. }
  569. #if defined(OSLinux)
  570. static int
  571. pid_is_exec(pid_t pid, const struct stat *esb)
  572. {
  573. char lname[32];
  574. char lcontents[_POSIX_PATH_MAX];
  575. const char deleted[] = " (deleted)";
  576. int nread;
  577. struct stat sb;
  578. sprintf(lname, "/proc/%d/exe", pid);
  579. nread = readlink(lname, lcontents, sizeof(lcontents));
  580. if (nread == -1)
  581. return 0;
  582. lcontents[nread] = '\0';
  583. if (strcmp(lcontents + nread - strlen(deleted), deleted) == 0)
  584. lcontents[nread - strlen(deleted)] = '\0';
  585. if (stat(lcontents, &sb) != 0)
  586. return 0;
  587. return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
  588. }
  589. static int
  590. pid_is_user(pid_t pid, uid_t uid)
  591. {
  592. struct stat sb;
  593. char buf[32];
  594. sprintf(buf, "/proc/%d", pid);
  595. if (stat(buf, &sb) != 0)
  596. return 0;
  597. return (sb.st_uid == uid);
  598. }
  599. static int
  600. pid_is_cmd(pid_t pid, const char *name)
  601. {
  602. char buf[32];
  603. FILE *f;
  604. int c;
  605. sprintf(buf, "/proc/%d/stat", pid);
  606. f = fopen(buf, "r");
  607. if (!f)
  608. return 0;
  609. while ((c = getc(f)) != EOF && c != '(')
  610. ;
  611. if (c != '(') {
  612. fclose(f);
  613. return 0;
  614. }
  615. /* this hopefully handles command names containing ')' */
  616. while ((c = getc(f)) != EOF && c == *name)
  617. name++;
  618. fclose(f);
  619. return (c == ')' && *name == '\0');
  620. }
  621. #endif /* OSLinux */
  622. #if defined(OSHURD)
  623. static void
  624. init_procset(void)
  625. {
  626. struct ps_context *context;
  627. error_t err;
  628. err = ps_context_create(getproc(), &context);
  629. if (err)
  630. error(1, err, "ps_context_create");
  631. err = proc_stat_list_create(context, &procset);
  632. if (err)
  633. error(1, err, "proc_stat_list_create");
  634. err = proc_stat_list_add_all(procset, 0, 0);
  635. if (err)
  636. error(1, err, "proc_stat_list_add_all");
  637. }
  638. static struct proc_stat *
  639. get_proc_stat (pid_t pid, ps_flags_t flags)
  640. {
  641. struct proc_stat *ps;
  642. ps_flags_t wanted_flags = PSTAT_PID | flags;
  643. if (!procset)
  644. init_procset();
  645. ps = proc_stat_list_pid_proc_stat(procset, pid);
  646. if (!ps)
  647. return NULL;
  648. if (proc_stat_set_flags(ps, wanted_flags))
  649. return NULL;
  650. if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
  651. return NULL;
  652. return ps;
  653. }
  654. static int
  655. pid_is_user(pid_t pid, uid_t uid)
  656. {
  657. struct proc_stat *ps;
  658. ps = get_proc_stat(pid, PSTAT_OWNER_UID);
  659. return ps && proc_stat_owner_uid(ps) == uid;
  660. }
  661. static int
  662. pid_is_cmd(pid_t pid, const char *name)
  663. {
  664. struct proc_stat *ps;
  665. ps = get_proc_stat(pid, PSTAT_ARGS);
  666. return ps && !strcmp(proc_stat_args(ps), name);
  667. }
  668. static int
  669. pid_is_running(pid_t pid)
  670. {
  671. return get_proc_stat(pid, 0) != NULL;
  672. }
  673. #else /* !OSHURD */
  674. static int
  675. pid_is_running(pid_t pid)
  676. {
  677. struct stat sb;
  678. char buf[32];
  679. sprintf(buf, "/proc/%d", pid);
  680. if (stat(buf, &sb) != 0) {
  681. if (errno!=ENOENT)
  682. fatal("Error stating %s: %s", buf, strerror(errno));
  683. return 0;
  684. }
  685. return 1;
  686. }
  687. #endif /* OSHURD */
  688. static void
  689. check(pid_t pid)
  690. {
  691. #if defined(OSLinux) || defined(OShpux)
  692. if (execname && !pid_is_exec(pid, &exec_stat))
  693. #elif defined(OSHURD) || defined(OSFreeBSD) || defined(OSNetBSD)
  694. /* I will try this to see if it works */
  695. if (execname && !pid_is_cmd(pid, execname))
  696. #endif
  697. return;
  698. if (userspec && !pid_is_user(pid, user_id))
  699. return;
  700. if (cmdname && !pid_is_cmd(pid, cmdname))
  701. return;
  702. if (start && !pid_is_running(pid))
  703. return;
  704. push(&found, pid);
  705. }
  706. static void
  707. do_pidfile(const char *name)
  708. {
  709. FILE *f;
  710. pid_t pid;
  711. f = fopen(name, "r");
  712. if (f) {
  713. if (fscanf(f, "%d", &pid) == 1)
  714. check(pid);
  715. fclose(f);
  716. } else if (errno != ENOENT)
  717. fatal("open pidfile %s: %s", name, strerror(errno));
  718. }
  719. /* WTA: this needs to be an autoconf check for /proc/pid existance.
  720. */
  721. #if defined(OSLinux) || defined (OSsunos)
  722. static void
  723. do_procinit(void)
  724. {
  725. DIR *procdir;
  726. struct dirent *entry;
  727. int foundany;
  728. pid_t pid;
  729. procdir = opendir("/proc");
  730. if (!procdir)
  731. fatal("opendir /proc: %s", strerror(errno));
  732. foundany = 0;
  733. while ((entry = readdir(procdir)) != NULL) {
  734. if (sscanf(entry->d_name, "%d", &pid) != 1)
  735. continue;
  736. foundany++;
  737. check(pid);
  738. }
  739. closedir(procdir);
  740. if (!foundany)
  741. fatal("nothing in /proc - not mounted?");
  742. }
  743. #endif /* OSLinux */
  744. #if defined(OSHURD)
  745. static int
  746. check_proc_stat (struct proc_stat *ps)
  747. {
  748. check(ps->pid);
  749. return 0;
  750. }
  751. static void
  752. do_procinit(void)
  753. {
  754. if (!procset)
  755. init_procset();
  756. proc_stat_list_for_each (procset, check_proc_stat);
  757. }
  758. #endif /* OSHURD */
  759. #ifdef HAVE_KVM_H
  760. static int
  761. pid_is_cmd(pid_t pid, const char *name)
  762. {
  763. kvm_t *kd;
  764. int nentries, argv_len=0;
  765. struct kinfo_proc *kp;
  766. char errbuf[_POSIX2_LINE_MAX], buf[_POSIX2_LINE_MAX];
  767. char **pid_argv_p;
  768. char *start_argv_0_p, *end_argv_0_p;
  769. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  770. if (kd == 0)
  771. errx(1, "%s", errbuf);
  772. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  773. errx(1, "%s", kvm_geterr(kd));
  774. if ((pid_argv_p = kvm_getargv(kd, kp, argv_len)) == 0)
  775. errx(1, "%s", kvm_geterr(kd));
  776. start_argv_0_p = *pid_argv_p;
  777. /* find and compare string */
  778. /* find end of argv[0] then copy and cut of str there. */
  779. if ((end_argv_0_p = strchr(*pid_argv_p, ' ')) == 0 )
  780. /* There seems to be no space, so we have the command
  781. * allready in its desired form. */
  782. start_argv_0_p = *pid_argv_p;
  783. else {
  784. /* Tests indicate that this never happens, since
  785. * kvm_getargv itselfe cuts of tailing stuff. This is
  786. * not what the manpage says, however. */
  787. strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
  788. buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
  789. start_argv_0_p = buf;
  790. }
  791. if (strlen(name) != strlen(start_argv_0_p))
  792. return 0;
  793. return (strcmp(name, start_argv_0_p) == 0) ? 1 : 0;
  794. }
  795. static int
  796. pid_is_user(pid_t pid, uid_t uid)
  797. {
  798. kvm_t *kd;
  799. int nentries; /* Value not used */
  800. uid_t proc_uid;
  801. struct kinfo_proc *kp;
  802. char errbuf[_POSIX2_LINE_MAX];
  803. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  804. if (kd == 0)
  805. errx(1, "%s", errbuf);
  806. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  807. errx(1, "%s", kvm_geterr(kd));
  808. if (kp->kp_proc.p_cred )
  809. kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
  810. &proc_uid, sizeof(uid_t));
  811. else
  812. return 0;
  813. return (proc_uid == (uid_t)uid);
  814. }
  815. static int
  816. pid_is_exec(pid_t pid, const char *name)
  817. {
  818. kvm_t *kd;
  819. int nentries;
  820. struct kinfo_proc *kp;
  821. char errbuf[_POSIX2_LINE_MAX], *pidexec;
  822. kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
  823. if (kd == 0)
  824. errx(1, "%s", errbuf);
  825. if ((kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &nentries)) == 0)
  826. errx(1, "%s", kvm_geterr(kd));
  827. pidexec = (&kp->kp_proc)->p_comm;
  828. if (strlen(name) != strlen(pidexec))
  829. return 0;
  830. return (strcmp(name, pidexec) == 0) ? 1 : 0;
  831. }
  832. static void
  833. do_procinit(void)
  834. {
  835. /* Nothing to do */
  836. }
  837. #endif /* OSOpenBSD */
  838. #if defined(OShpux)
  839. static int
  840. pid_is_user(pid_t pid, uid_t uid)
  841. {
  842. struct pst_status pst;
  843. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  844. return 0;
  845. return ((uid_t) pst.pst_uid == uid);
  846. }
  847. static int
  848. pid_is_cmd(pid_t pid, const char *name)
  849. {
  850. struct pst_status pst;
  851. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  852. return 0;
  853. return (strcmp(pst.pst_ucomm, name) == 0);
  854. }
  855. static int
  856. pid_is_exec(pid_t pid, const struct stat *esb)
  857. {
  858. struct pst_status pst;
  859. if (pstat_getproc(&pst, sizeof(pst), (size_t) 0, (int) pid) < 0)
  860. return 0;
  861. return ((dev_t) pst.pst_text.psf_fsid.psfs_id == esb->st_dev
  862. && (ino_t) pst.pst_text.psf_fileid == esb->st_ino);
  863. }
  864. static void
  865. do_procinit(void)
  866. {
  867. struct pst_status pst[10];
  868. int i, count;
  869. int idx = 0;
  870. while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
  871. for (i = 0; i < count; i++)
  872. check(pst[i].pst_pid);
  873. idx = pst[count - 1].pst_idx + 1;
  874. }
  875. }
  876. #endif /* OShpux */
  877. static void
  878. do_findprocs(void)
  879. {
  880. clear(&found);
  881. if (pidfile)
  882. do_pidfile(pidfile);
  883. else
  884. do_procinit();
  885. }
  886. /* return 1 on failure */
  887. static void
  888. do_stop(int signal_nr, int quietmode, int *n_killed, int *n_notkilled, int retry_nr)
  889. {
  890. struct pid_list *p;
  891. do_findprocs();
  892. *n_killed = 0;
  893. *n_notkilled = 0;
  894. if (!found)
  895. return;
  896. clear(&killed);
  897. for (p = found; p; p = p->next) {
  898. if (testmode) {
  899. printf("Would send signal %d to %d.\n",
  900. signal_nr, p->pid);
  901. (*n_killed)++;
  902. } else if (kill(p->pid, signal_nr) == 0) {
  903. push(&killed, p->pid);
  904. (*n_killed)++;
  905. } else {
  906. printf("%s: warning: failed to kill %d: %s\n",
  907. progname, p->pid, strerror(errno));
  908. (*n_notkilled)++;
  909. }
  910. }
  911. if (quietmode < 0 && killed) {
  912. printf("Stopped %s (pid", what_stop);
  913. for (p = killed; p; p = p->next)
  914. printf(" %d", p->pid);
  915. putchar(')');
  916. if (retry_nr > 0)
  917. printf(", retry #%d", retry_nr);
  918. printf(".\n");
  919. }
  920. }
  921. static void
  922. set_what_stop(const char *str)
  923. {
  924. strncpy(what_stop, str, sizeof(what_stop));
  925. what_stop[sizeof(what_stop)-1] = '\0';
  926. }
  927. static int
  928. run_stop_schedule(void)
  929. {
  930. int r, position, n_killed, n_notkilled, value, ratio, anykilled, retry_nr;
  931. struct timeval stopat, before, after, interval, maxinterval;
  932. if (testmode) {
  933. if (schedule != NULL) {
  934. printf("Ignoring --retry in test mode\n");
  935. schedule = NULL;
  936. }
  937. }
  938. if (cmdname)
  939. set_what_stop(cmdname);
  940. else if (execname)
  941. set_what_stop(execname);
  942. else if (pidfile)
  943. sprintf(what_stop, "process in pidfile `%.200s'", pidfile);
  944. else if (userspec)
  945. sprintf(what_stop, "process(es) owned by `%.200s'", userspec);
  946. else
  947. fatal("internal error, please report");
  948. anykilled = 0;
  949. retry_nr = 0;
  950. if (schedule == NULL) {
  951. do_stop(signal_nr, quietmode, &n_killed, &n_notkilled, 0);
  952. if (n_notkilled > 0 && quietmode <= 0)
  953. printf("%d pids were not killed\n", n_notkilled);
  954. if (n_killed)
  955. anykilled = 1;
  956. goto x_finished;
  957. }
  958. for (position = 0; position < schedule_length; ) {
  959. value= schedule[position].value;
  960. n_notkilled = 0;
  961. switch (schedule[position].type) {
  962. case sched_goto:
  963. position = value;
  964. continue;
  965. case sched_signal:
  966. do_stop(value, quietmode, &n_killed, &n_notkilled, retry_nr++);
  967. if (!n_killed)
  968. goto x_finished;
  969. else
  970. anykilled = 1;
  971. goto next_item;
  972. case sched_timeout:
  973. /* We want to keep polling for the processes, to see if they've exited,
  974. * or until the timeout expires.
  975. *
  976. * This is a somewhat complicated algorithm to try to ensure that we
  977. * notice reasonably quickly when all the processes have exited, but
  978. * don't spend too much CPU time polling. In particular, on a fast
  979. * machine with quick-exiting daemons we don't want to delay system
  980. * shutdown too much, whereas on a slow one, or where processes are
  981. * taking some time to exit, we want to increase the polling
  982. * interval.
  983. *
  984. * The algorithm is as follows: we measure the elapsed time it takes
  985. * to do one poll(), and wait a multiple of this time for the next
  986. * poll. However, if that would put us past the end of the timeout
  987. * period we wait only as long as the timeout period, but in any case
  988. * we always wait at least MIN_POLL_INTERVAL (20ms). The multiple
  989. * (`ratio') starts out as 2, and increases by 1 for each poll to a
  990. * maximum of 10; so we use up to between 30% and 10% of the
  991. * machine's resources (assuming a few reasonable things about system
  992. * performance).
  993. */
  994. xgettimeofday(&stopat);
  995. stopat.tv_sec += value;
  996. ratio = 1;
  997. for (;;) {
  998. xgettimeofday(&before);
  999. if (timercmp(&before,&stopat,>))
  1000. goto next_item;
  1001. do_stop(0, 1, &n_killed, &n_notkilled, 0);
  1002. if (!n_killed)
  1003. goto x_finished;
  1004. xgettimeofday(&after);
  1005. if (!timercmp(&after,&stopat,<))
  1006. goto next_item;
  1007. if (ratio < 10)
  1008. ratio++;
  1009. TVCALC(interval, ratio * (TVELEM(&after) - TVELEM(&before) + TVADJUST));
  1010. TVCALC(maxinterval, TVELEM(&stopat) - TVELEM(&after) + TVADJUST);
  1011. if (timercmp(&interval,&maxinterval,>))
  1012. interval = maxinterval;
  1013. if (interval.tv_sec == 0 &&
  1014. interval.tv_usec <= MIN_POLL_INTERVAL)
  1015. interval.tv_usec = MIN_POLL_INTERVAL;
  1016. r = select(0,0,0,0,&interval);
  1017. if (r < 0 && errno != EINTR)
  1018. fatal("select() failed for pause: %s",
  1019. strerror(errno));
  1020. }
  1021. default:
  1022. assert(!"schedule[].type value must be valid");
  1023. }
  1024. next_item:
  1025. position++;
  1026. }
  1027. if (quietmode <= 0)
  1028. printf("Program %s, %d process(es), refused to die.\n",
  1029. what_stop, n_killed);
  1030. return 2;
  1031. x_finished:
  1032. if (!anykilled) {
  1033. if (quietmode <= 0)
  1034. printf("No %s found running; none killed.\n", what_stop);
  1035. return exitnodo;
  1036. } else {
  1037. return 0;
  1038. }
  1039. }
  1040. int
  1041. main(int argc, char **argv)
  1042. {
  1043. int devnull_fd = -1;
  1044. #ifdef HAVE_TIOCNOTTY
  1045. int tty_fd = -1;
  1046. #endif
  1047. progname = argv[0];
  1048. parse_options(argc, argv);
  1049. argc -= optind;
  1050. argv += optind;
  1051. if (execname) {
  1052. char *fullexecname;
  1053. if (changeroot) {
  1054. int fullexecname_len = strlen(changeroot) + 1 +
  1055. strlen(execname) + 1;
  1056. fullexecname = xmalloc(fullexecname_len);
  1057. snprintf(fullexecname, fullexecname_len, "%s/%s",
  1058. changeroot, execname);
  1059. } else
  1060. fullexecname = execname;
  1061. if (stat(fullexecname, &exec_stat))
  1062. fatal("stat %s: %s", fullexecname, strerror(errno));
  1063. if (fullexecname != execname)
  1064. free(fullexecname);
  1065. }
  1066. if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
  1067. struct passwd *pw;
  1068. pw = getpwnam(userspec);
  1069. if (!pw)
  1070. fatal("user `%s' not found\n", userspec);
  1071. user_id = pw->pw_uid;
  1072. }
  1073. if (changegroup && sscanf(changegroup, "%d", &runas_gid) != 1) {
  1074. struct group *gr = getgrnam(changegroup);
  1075. if (!gr)
  1076. fatal("group `%s' not found\n", changegroup);
  1077. runas_gid = gr->gr_gid;
  1078. }
  1079. if (changeuser && sscanf(changeuser, "%d", &runas_uid) != 1) {
  1080. struct passwd *pw = getpwnam(changeuser);
  1081. if (!pw)
  1082. fatal("user `%s' not found\n", changeuser);
  1083. runas_uid = pw->pw_uid;
  1084. if (changegroup == NULL) { /* pass the default group of this user */
  1085. changegroup = ""; /* just empty */
  1086. runas_gid = pw->pw_gid;
  1087. }
  1088. if (access(pw->pw_dir, F_OK) == 0)
  1089. setenv("HOME", pw->pw_dir, 1);
  1090. }
  1091. if (stop) {
  1092. int i = run_stop_schedule();
  1093. exit(i);
  1094. }
  1095. do_findprocs();
  1096. if (found) {
  1097. if (quietmode <= 0)
  1098. printf("%s already running.\n", execname ? execname : "process");
  1099. exit(exitnodo);
  1100. }
  1101. if (testmode) {
  1102. printf("Would start %s ", startas);
  1103. while (argc-- > 0)
  1104. printf("%s ", *argv++);
  1105. if (changeuser != NULL) {
  1106. printf(" (as user %s[%d]", changeuser, runas_uid);
  1107. if (changegroup != NULL)
  1108. printf(", and group %s[%d])", changegroup, runas_gid);
  1109. else
  1110. printf(")");
  1111. }
  1112. if (changeroot != NULL)
  1113. printf(" in directory %s", changeroot);
  1114. if (nicelevel)
  1115. printf(", and add %i to the priority", nicelevel);
  1116. printf(".\n");
  1117. exit(0);
  1118. }
  1119. if (quietmode < 0)
  1120. printf("Starting %s...\n", startas);
  1121. *--argv = startas;
  1122. if (background) { /* ok, we need to detach this process */
  1123. int i;
  1124. if (quietmode < 0)
  1125. printf("Detaching to start %s...", startas);
  1126. i = fork();
  1127. if (i<0) {
  1128. fatal("Unable to fork.\n");
  1129. }
  1130. if (i) { /* parent */
  1131. if (quietmode < 0)
  1132. printf("done.\n");
  1133. exit(0);
  1134. }
  1135. /* child continues here */
  1136. #ifdef HAVE_TIOCNOTTY
  1137. tty_fd=open("/dev/tty", O_RDWR);
  1138. #endif
  1139. devnull_fd=open("/dev/null", O_RDWR);
  1140. }
  1141. if (nicelevel) {
  1142. errno=0;
  1143. if ((nice(nicelevel)==-1) && (errno!=0))
  1144. fatal("Unable to alter nice level by %i: %s", nicelevel,
  1145. strerror(errno));
  1146. }
  1147. if (umask_value >= 0)
  1148. umask(umask_value);
  1149. if (mpidfile && pidfile != NULL) { /* user wants _us_ to make the pidfile :) */
  1150. FILE *pidf = fopen(pidfile, "w");
  1151. pid_t pidt = getpid();
  1152. if (pidf == NULL)
  1153. fatal("Unable to open pidfile `%s' for writing: %s", pidfile,
  1154. strerror(errno));
  1155. fprintf(pidf, "%d\n", pidt);
  1156. fclose(pidf);
  1157. }
  1158. if (changeroot != NULL) {
  1159. if (chdir(changeroot) < 0)
  1160. fatal("Unable to chdir() to %s", changeroot);
  1161. if (chroot(changeroot) < 0)
  1162. fatal("Unable to chroot() to %s", changeroot);
  1163. }
  1164. if (chdir(changedir) < 0)
  1165. fatal("Unable to chdir() to %s", changedir);
  1166. if (changeuser != NULL) {
  1167. if (setgid(runas_gid))
  1168. fatal("Unable to set gid to %d", runas_gid);
  1169. if (initgroups(changeuser, runas_gid))
  1170. fatal("Unable to set initgroups() with gid %d", runas_gid);
  1171. if (setuid(runas_uid))
  1172. fatal("Unable to set uid to %s", changeuser);
  1173. }
  1174. if (background) { /* continue background setup */
  1175. int i;
  1176. #ifdef HAVE_TIOCNOTTY
  1177. /* change tty */
  1178. ioctl(tty_fd, TIOCNOTTY, 0);
  1179. close(tty_fd);
  1180. #endif
  1181. if (umask_value < 0)
  1182. umask(022); /* set a default for dumb programs */
  1183. dup2(devnull_fd,0); /* stdin */
  1184. dup2(devnull_fd,1); /* stdout */
  1185. dup2(devnull_fd,2); /* stderr */
  1186. #if defined(OShpux)
  1187. /* now close all extra fds */
  1188. for (i=sysconf(_SC_OPEN_MAX)-1; i>=3; --i) close(i);
  1189. #else
  1190. /* now close all extra fds */
  1191. for (i=getdtablesize()-1; i>=3; --i) close(i);
  1192. #endif
  1193. /* create a new session */
  1194. #ifdef HAVE_SETSID
  1195. setsid();
  1196. #else
  1197. setpgid(0,0);
  1198. #endif
  1199. }
  1200. execv(startas, argv);
  1201. fatal("Unable to start %s: %s", startas, strerror(errno));
  1202. }