Skip to content

Instantly share code, notes, and snippets.

@jshardy
Last active February 26, 2019 09:25
Show Gist options
  • Save jshardy/7597ae4644a26a5b3ffa352c6a7e2360 to your computer and use it in GitHub Desktop.
Save jshardy/7597ae4644a26a5b3ffa352c6a7e2360 to your computer and use it in GitHub Desktop.
Create Process/Redirect Output
pid_t create_process(char *cmd, int file_input, int file_output)
{
pid_t pid = -1;
char **array_args = NULL;
pid = fork();
if(pid == 0)
{
//child
quick_dup(file_input, file_output);
execvp(cmd, cmd);
//if execvp fails output error and kill child.
fprintf(stderr, COLOR_RED "%s: Bad command or filename?\n" COLOR_RESET, strtok(cmd, " "));
exit(EXIT_FAILURE);
}
// Parent
return pid;
}
void quick_dup(int file_input, int file_output)
{
//avoid closing 0 for first input
if(file_input != STDIN_FILENO)
{
dup2(file_input, STDIN_FILENO);
close(file_input);
}
//avoid closing output for last output
if(file_output != STDOUT_FILENO)
{
dup2(file_output, STDOUT_FILENO);
close(file_output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment