Конечно, просто fork
и exec
: используйте fork
для создания нового процесса и, в дочернем процессе, используйте exec
для запуска оболочки с вашей командой.execv
принимает аргументы, которые вы обычно предоставляете оболочке.
Ваш код может выглядеть так:
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
}
дочерний процесс отправит сигнал SIGCHLD
, когда он умрет.Этот код, указанный в стандарте POSIX (SUSv4), будет обрабатывать следующее:
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\n";
write(2, msg, sizeof msg - 1);
}
else if (waitpid(sinfo->si_pid, &status, 0) == -1)
{
static char msg[] = "waitpid() failed\n";
write(2, msg, sizeof msg - 1);
}
else if (!WIFEXITED(status))
{
static char msg[] = "WIFEXITED was false\n";
write(2, msg, sizeof msg - 1);
}
else
{
int code = WEXITSTATUS(status);
char buf[2];
buf[0] = '0' + code;
buf[1] = '\n';
write(1, buf, 2);
}
}