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 (at) 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 <strings.h> 34 #include <errno.h> 35 #include "test.h" 36 #include "lapi/namespaces_constants.h" 37 #include "ns_common.h" 38 39 char *TCID = "ns_create"; 40 41 42 void print_help(void) 43 { 44 int i; 45 46 printf("usage: ns_create <%s", params[0].name); 47 48 for (i = 1; params[i].name; i++) 49 printf("|,%s", params[i].name); 50 printf(">\nThe only argument is a comma separated list " 51 "of namespaces to create.\nExample: ns_create net,ipc\n"); 52 } 53 54 static int child_fn(void *arg LTP_ATTRIBUTE_UNUSED) 55 { 56 int i; 57 58 if (setsid() == -1) { 59 tst_resm(TINFO | TERRNO, "setsid"); 60 exit(1); 61 } 62 63 if (chdir("/") == -1) { 64 tst_resm(TINFO | TERRNO, "chdir"); 65 exit(1); 66 } 67 68 /* close all inherrited file descriptors */ 69 for (i = 0; i < sysconf(_SC_OPEN_MAX); i++) 70 close(i); 71 72 pause(); 73 return 0; 74 } 75 76 /* 77 * ./ns_create <ipc,mnt,net,pid,user,uts> 78 */ 79 int main(int argc, char *argv[]) 80 { 81 int pid, flags; 82 char *token; 83 84 if (argc < 2) { 85 print_help(); 86 return 1; 87 } 88 89 flags = 0; 90 while ((token = strsep(&argv[1], ","))) { 91 struct param *p = get_param(token); 92 93 if (!p) { 94 tst_resm(TINFO, "Unknown namespace: %s", token); 95 print_help(); 96 return 1; 97 } 98 99 flags |= p->flag; 100 } 101 102 pid = ltp_clone_quick(flags | SIGCHLD, child_fn, NULL); 103 if (pid == -1) { 104 tst_resm(TINFO | TERRNO, "ltp_clone_quick"); 105 return 1; 106 } 107 108 printf("%d", pid); 109 return 0; 110 } 111