Sure, just fork
and exec
: use fork
to create a new process and, in the child process, use exec
to start the shell with your command. execv
takes the arguments you would normally give to the shell.
Your code could look like this:
pid_t child_pid = fork();
if (child_pid == 0)
{ // in child
/* set up arguments */
// launch here
execv("/bin/sh", args);
// if you ever get here, there's been an error - handle it
}
else if (child_pid < 0)
{ // handle error
}
the child process will send a SIGCHLD
signal when it dies. This code quoted from the POSIX standard (SUSv4) will handle that:
static void
handle_sigchld(int signum, siginfo_t *sinfo, void *unused)
{
int status;
/*
* Obtain status information for the child which
* caused the SIGCHLD signal and write its exit code
* to stdout.
*/
if (sinfo->si_code != CLD_EXITED)
{
static char msg[] = "wrong si_code
";
write(2, msg, sizeof msg - 1);
}
else if (waitpid(sinfo->si_pid, &status, 0) == -1)
{
static char msg[] = "waitpid() failed
";
write(2, msg, sizeof msg - 1);
}
else if (!WIFEXITED(status))
{
static char msg[] = "WIFEXITED was false
";
write(2, msg, sizeof msg - 1);
}
else
{
int code = WEXITSTATUS(status);
char buf[2];
buf[0] = '0' + code;
buf[1] = '
';
write(1, buf, 2);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…