1 /* Copyright (c) 2015 Red Hat, Inc.
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of version 2 the GNU General Public License as
5 * published by the Free Software Foundation.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *
15 * Written by Matus Marhefka <mmarhefk@redhat.com>
16 *
17 ***********************************************************************
18 * Creates a child process in the new specified namespace(s), child is then
19 * daemonized and is running in the background. PID of the daemonized child
20 * process is printed on the stdout. As the new namespace(s) is(are) maintained
21 * by the daemonized child process it(they) can be removed by killing this
22 * process.
23 *
24 */
25
26 #define _GNU_SOURCE
27 #include <sched.h>
28 #include <sys/syscall.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <string.h>
33 #include <errno.h>
34 #include "test.h"
35 #include "lapi/namespaces_constants.h"
36 #include "ns_common.h"
37
38 char *TCID = "ns_create";
39
40
print_help(void)41 void print_help(void)
42 {
43 int i;
44
45 printf("usage: ns_create <%s", params[0].name);
46
47 for (i = 1; params[i].name; i++)
48 printf("|,%s", params[i].name);
49 printf(">\nThe only argument is a comma separated list "
50 "of namespaces to create.\nExample: ns_create net,ipc\n");
51 }
52
child_fn(void * arg LTP_ATTRIBUTE_UNUSED)53 static int child_fn(void *arg LTP_ATTRIBUTE_UNUSED)
54 {
55 int i;
56
57 if (setsid() == -1) {
58 tst_resm(TINFO | TERRNO, "setsid");
59 exit(1);
60 }
61
62 if (chdir("/") == -1) {
63 tst_resm(TINFO | TERRNO, "chdir");
64 exit(1);
65 }
66
67 /* close all inherrited file descriptors */
68 for (i = 0; i < sysconf(_SC_OPEN_MAX); i++)
69 close(i);
70
71 pause();
72 return 0;
73 }
74
75 /*
76 * ./ns_create <ipc,mnt,net,pid,user,uts>
77 */
main(int argc,char * argv[])78 int main(int argc, char *argv[])
79 {
80 int pid, flags;
81 char *token;
82
83 if (argc < 2) {
84 print_help();
85 return 1;
86 }
87
88 flags = 0;
89 while ((token = strsep(&argv[1], ","))) {
90 struct param *p = get_param(token);
91
92 if (!p) {
93 tst_resm(TINFO, "Unknown namespace: %s", token);
94 print_help();
95 return 1;
96 }
97
98 flags |= p->flag;
99 }
100
101 pid = ltp_clone_quick(flags | SIGCHLD, child_fn, NULL);
102 if (pid == -1) {
103 tst_resm(TINFO | TERRNO, "ltp_clone_quick");
104 return 1;
105 }
106
107 printf("%d", pid);
108 return 0;
109 }
110