New upstream version 18.02
[deb_dpdk.git] / test / test / process.h
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4
5 #ifndef _PROCESS_H_
6 #define _PROCESS_H_
7
8 #ifdef RTE_EXEC_ENV_BSDAPP
9 #define self "curproc"
10 #define exe "file"
11 #else
12 #define self "self"
13 #define exe "exe"
14 #endif
15
16 /*
17  * launches a second copy of the test process using the given argv parameters,
18  * which should include argv[0] as the process name. To identify in the
19  * subprocess the source of the call, the env_value parameter is set in the
20  * environment as $RTE_TEST
21  */
22 static inline int
23 process_dup(const char *const argv[], int numargs, const char *env_value)
24 {
25         int num;
26         char *argv_cpy[numargs + 1];
27         int i, fd, status;
28         char path[32];
29
30         pid_t pid = fork();
31         if (pid < 0)
32                 return -1;
33         else if (pid == 0) {
34                 /* make a copy of the arguments to be passed to exec */
35                 for (i = 0; i < numargs; i++)
36                         argv_cpy[i] = strdup(argv[i]);
37                 argv_cpy[i] = NULL;
38                 num = numargs;
39
40                 /* close all open file descriptors, check /proc/self/fd to only
41                  * call close on open fds. Exclude fds 0, 1 and 2*/
42                 for (fd = getdtablesize(); fd > 2; fd-- ) {
43                         snprintf(path, sizeof(path), "/proc/" exe "/fd/%d", fd);
44                         if (access(path, F_OK) == 0)
45                                 close(fd);
46                 }
47                 printf("Running binary with argv[]:");
48                 for (i = 0; i < num; i++)
49                         printf("'%s' ", argv_cpy[i]);
50                 printf("\n");
51
52                 /* set the environment variable */
53                 if (setenv(RECURSIVE_ENV_VAR, env_value, 1) != 0)
54                         rte_panic("Cannot export environment variable\n");
55                 if (execv("/proc/" self "/" exe, argv_cpy) < 0)
56                         rte_panic("Cannot exec\n");
57         }
58         /* parent process does a wait */
59         while (wait(&status) != pid)
60                 ;
61         return status;
62 }
63
64 #endif /* _PROCESS_H_ */