I have a CLI, one of the commands is entering into Linux bash shell. This is the code which does it using fork & execv:
if ((pid = fork()) < 0) {
syslog_debug(LOG_ERR, "Could not fork");
}
if (pid == 0) {
/* In child, open the child's side of the tty. */
int i;
for(i = 0; i <= maxfd; i++)
{
close(i);
}
/* make new process group */
setsid();
if ((fd[0] = open(tty_name, O_RDWR /*| O_NOCTTY*/)) < 0) {
syslog_debug(LOG_ERR, "Could not open tty");
exit(1);
}
fd[1] = dup(0);
fd[2] = dup(0);
/* exec shell, with correct argv and env */
execv("/bin/sh", (char *const *)argv_init);
exit(1);
}
I want to replace the fork/execv and to use posix_spawn instead:
ret = posix_spawn_file_actions_init(&action);
pipe(fd);
for(i = 0; i <= maxfd; i++)
{
ret = posix_spawn_file_actions_addclose (&action, i);
}
ret = posix_spawn_file_actions_adddup2 (&action, fd[1], 0);
ret = posix_spawn_file_actions_adddup2 (&action, fd[2], 0);
ret = posix_spawn_file_actions_addopen (&action, STDOUT_FILENO, tty_name, O_RDWR, 0);
char* argv[] = { "/bin/sh", "-c", "bash", NULL };
int status;
extern char **environ;
posix_spawnattr_t attr = { 0 };
snprintf( cmd, sizeof(cmd), "bash");
status = posix_spawn( &pid,
argv[0],
action /*__file_actions*/,
&attr,
argv,
environ );
posix_spawn_file_actions_destroy(&action);
But it doesn't work. Any help?