OSDN Git Service

Merge catv back into cat as discussed on the list. Add comments about infrastructure...
[android-x86/external-toybox.git] / toys / other / oneit.c
1 /* oneit.c - tiny init replacement to launch a single child process.
2  *
3  * Copyright 2005, 2007 by Rob Landley <rob@landley.net>.
4
5 USE_ONEIT(NEWTOY(oneit, "^<1c:p", TOYFLAG_SBIN))
6
7 config ONEIT
8   bool "oneit"
9   default y
10   help
11     usage: oneit [-p] [-c /dev/tty0] command [...]
12
13     A simple init program that runs a single supplied command line with a
14     controlling tty (so CTRL-C can kill it).
15
16     -p  Power off instead of rebooting when command exits.
17     -c  Which console device to use.
18
19     The oneit command runs the supplied command line as a child process
20     (because PID 1 has signals blocked), attached to /dev/tty0, in its
21     own session. Then oneit reaps zombies until the child exits, at
22     which point it reboots (or with -p, powers off) the system.
23 */
24
25 #define FOR_oneit
26 #include "toys.h"
27 #include <sys/reboot.h>
28
29 GLOBALS(
30   char *console;
31 )
32
33 // The minimum amount of work necessary to get ctrl-c and such to work is:
34 //
35 // - Fork a child (PID 1 is special: can't exit, has various signals blocked).
36 // - Do a setsid() (so we have our own session).
37 // - In the child, attach stdio to /dev/tty0 (/dev/console is special)
38 // - Exec the rest of the command line.
39 //
40 // PID 1 then reaps zombies until the child process it spawned exits, at which
41 // point it calls sync() and reboot().  I could stick a kill -1 in there.
42
43
44 void oneit_main(void)
45 {
46   int i;
47   pid_t pid;
48
49   // Create a new child process.
50   pid = vfork();
51   if (pid) {
52
53     // pid 1 just reaps zombies until it gets its child, then halts the system.
54     while (pid != wait(&i));
55     sync();
56
57     // PID 1 can't call reboot() because it kills the task that calls it,
58     // which causes the kernel to panic before the actual reboot happens.
59     if (!vfork()) reboot((toys.optflags & FLAG_p) ? RB_POWER_OFF : RB_AUTOBOOT);
60     sleep(5);
61     _exit(1);
62   }
63
64   // Redirect stdio to /dev/tty0, with new session ID, so ctrl-c works.
65   setsid();
66   for (i=0; i<3; i++) {
67     close(i);
68     // Remember, O_CLOEXEC is backwards for xopen()
69     xopen(TT.console ? TT.console : "/dev/tty0", O_RDWR|O_CLOEXEC);
70   }
71
72   // Can't xexec() here, because we vforked so we don't want to error_exit().
73   toy_exec(toys.optargs);
74   execvp(*toys.optargs, toys.optargs);
75   _exit(127);
76 }