2 * switchroot.c - switch to new root directory and start init.
4 * Copyright 2002-2008 Red Hat, Inc. All rights reserved.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * Peter Jones <pjones@redhat.com>
21 * Jeremy Katz <katzj@redhat.com>
26 #include <sys/mount.h>
27 #include <sys/types.h>
29 #include <sys/param.h>
43 #define MNT_DETACH 0x2
52 static int switchroot(const char *newroot
)
54 /* Don't try to unmount the old "/", there's no way to do it. */
55 const char *umounts
[] = { "/dev", "/proc", "/sys", NULL
};
59 for (i
= 0; umounts
[i
] != NULL
; i
++) {
60 char newmount
[PATH_MAX
];
61 strcpy(newmount
, newroot
);
62 strcat(newmount
, umounts
[i
]);
63 if (mount(umounts
[i
], newmount
, NULL
, MS_MOVE
, NULL
) < 0) {
64 fprintf(stderr
, "Error mount moving old %s %s %m\n",
65 umounts
[i
], newmount
);
66 fprintf(stderr
, "Forcing unmount of %s\n", umounts
[i
]);
67 umount2(umounts
[i
], MNT_FORCE
);
71 if (chdir(newroot
) < 0) {
73 fprintf(stderr
, "switchroot: chdir failed: %m\n");
78 if (mount(newroot
, "/", NULL
, MS_MOVE
, NULL
) < 0) {
80 fprintf(stderr
, "switchroot: mount failed: %m\n");
87 fprintf(stderr
, "switchroot: chroot failed: %m\n");
94 static void usage(FILE *output
)
96 fprintf(output
, "usage: switchroot <newrootdir> <init> <args to init>\n");
102 int main(int argc
, char *argv
[])
104 char *newroot
= argv
[1];
105 char *init
= argv
[2];
106 char **initargs
= &argv
[2];
108 if (newroot
== NULL
|| newroot
[0] == '\0' ||
109 init
== NULL
|| init
[0] == '\0' ) {
113 if (switchroot(newroot
) < 0) {
114 fprintf(stderr
, "switchroot has failed. Sorry.\n");
117 if (access(initargs
[0], X_OK
))
118 fprintf(stderr
, "WARNING: can't access %s\n", initargs
[0]);
119 execv(initargs
[0], initargs
);
123 * vim:noet:ts=8:sw=8:sts=8