Shows how to execute commands in subprocesses
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
bool parse_exec_and_wait(char* cmd_line)
{
pid_t pid = fork();
if(pid < 0)
{
perror("Fork failed");
return false;
}
else if(pid == 0)
{
size_t max_args = 31;
char* args[32];
int arg = 0;
char *p, *s;
const char *delim = " \t\r\n\0";
p = strtok_r(cmd_line, delim, &s);
while(p)
{
if(arg == max_args) break;
args[arg++] = p;
p = strtok_r(NULL, delim, &s);
}
args[arg] = NULL;
execvp(args[0], args);
printf("Failed to execute '%s'\n", cmd_line);
return false;
}
else
{
int status = 0;
waitpid(pid, &status, 0);
if(WIFSIGNALED(status))
printf("Terminated by signal %d\n", WTERMSIG(status));
}
return true;
}
int main(int argc, const char* argv[])
{
size_t size = 1023;
char buffer[1024];
while(fputs("$>", stdout), fgets(buffer, size, stdin))
{
buffer[size] = '\0';
if(strncmp(buffer, "exit", 4) == 0) break;
else if(!parse_exec_and_wait(buffer)) return 1;
}
fputc('\n', stdout);
return 0;
}