|
@ -177,7 +177,7 @@ int check_redirect(char **args, char *redirect_filename, char **redirect_args) |
|
|
|
|
|
|
|
|
int execute(char *cmdline, char **args) |
|
|
int execute(char *cmdline, char **args) |
|
|
{ |
|
|
{ |
|
|
int bg = 0, i = 0, redirect_flag = 0; |
|
|
|
|
|
|
|
|
int bg = 0, i = 0, redirect_flag = 0, fd = 1; |
|
|
pid_t pid; |
|
|
pid_t pid; |
|
|
char *redirect_filename = NULL; |
|
|
char *redirect_filename = NULL; |
|
|
redirect_filename = (char *)calloc(32, sizeof(char)); |
|
|
redirect_filename = (char *)calloc(32, sizeof(char)); |
|
@ -187,7 +187,6 @@ int execute(char *cmdline, char **args) |
|
|
sigaddset(&mask_all, SIGCHLD); |
|
|
sigaddset(&mask_all, SIGCHLD); |
|
|
bg = parseline(cmdline, args); |
|
|
bg = parseline(cmdline, args); |
|
|
redirect_flag = check_redirect(args, redirect_filename, redirect_args); |
|
|
redirect_flag = check_redirect(args, redirect_filename, redirect_args); |
|
|
printf("%d %s %s %s %s\n", redirect_flag, redirect_filename, redirect_args[0], redirect_args[1], redirect_args[2]); |
|
|
|
|
|
|
|
|
|
|
|
if (args[0] == NULL) |
|
|
if (args[0] == NULL) |
|
|
{ |
|
|
{ |
|
@ -200,6 +199,19 @@ int execute(char *cmdline, char **args) |
|
|
|
|
|
|
|
|
if ((pid = fork()) == 0) /* Child process */ |
|
|
if ((pid = fork()) == 0) /* Child process */ |
|
|
{ |
|
|
{ |
|
|
|
|
|
if (redirect_flag == 1) |
|
|
|
|
|
{ |
|
|
|
|
|
fd = open(redirect_filename, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR); |
|
|
|
|
|
close(1); |
|
|
|
|
|
dup2(1, fd); |
|
|
|
|
|
} |
|
|
|
|
|
else if (redirect_flag == 2) |
|
|
|
|
|
{ |
|
|
|
|
|
fd = open(redirect_filename, O_RDONLY, S_IRUSR); |
|
|
|
|
|
close(0); |
|
|
|
|
|
dup2(0, fd); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
/* The child process inherits the parent's signal mask and will inherit it after exec,
|
|
|
/* The child process inherits the parent's signal mask and will inherit it after exec,
|
|
|
so it needs to restore the signal mask before executing. */ |
|
|
so it needs to restore the signal mask before executing. */ |
|
|
sigprocmask(SIG_SETMASK, &mask_prev, NULL); /* Child process, unblock SIGCHLD */ |
|
|
sigprocmask(SIG_SETMASK, &mask_prev, NULL); /* Child process, unblock SIGCHLD */ |
|
@ -210,6 +222,8 @@ int execute(char *cmdline, char **args) |
|
|
if (execvp(args[0], args) <= 0) |
|
|
if (execvp(args[0], args) <= 0) |
|
|
{ |
|
|
{ |
|
|
printf("%s: Command not found\n", args[0]); |
|
|
printf("%s: Command not found\n", args[0]); |
|
|
|
|
|
free(redirect_filename); |
|
|
|
|
|
free(redirect_args); |
|
|
exit(0); |
|
|
exit(0); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
@ -236,6 +250,9 @@ int execute(char *cmdline, char **args) |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
close(fd); |
|
|
|
|
|
free(redirect_filename); |
|
|
|
|
|
free(redirect_args); |
|
|
return 1; |
|
|
return 1; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|