diff options
Diffstat (limited to '21sh/myredir')
| -rw-r--r-- | 21sh/myredir/myredir.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/21sh/myredir/myredir.c b/21sh/myredir/myredir.c new file mode 100644 index 0000000..071a8bf --- /dev/null +++ b/21sh/myredir/myredir.c @@ -0,0 +1,46 @@ +#include <err.h> +#include <fcntl.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +int main(int argc, char *argv[]) +{ + if (argc < 3) + { + fprintf(stderr, "Missing argument\n"); + return 2; + } + // Save stdout + int stdout_dup = dup(STDOUT_FILENO); + + int file_fd = open(argv[1], O_CREAT | O_WRONLY, 0644); + + // Redirect stdout to the file + dup2(file_fd, STDOUT_FILENO); + + int status; + + pid_t pid = fork(); + if (pid == 0) + { + execvp(argv[2], argv + 2); + return 127; + } + else + { + waitpid(pid, &status, 0); + if (WIFEXITED(status)) + { + status = WEXITSTATUS(status); + fflush(stdout); + dup2(stdout_dup, STDOUT_FILENO); + close(stdout_dup); + } + if (status != 127) + printf("%s exited with %d!\n", argv[2], status); + else + fprintf(stderr, "Missing command\n"); + return status == 127; + } +} |
