Last active
February 26, 2019 09:25
-
-
Save jshardy/7597ae4644a26a5b3ffa352c6a7e2360 to your computer and use it in GitHub Desktop.
Create Process/Redirect Output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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