From 967be9e750221ab2ab783f95df79bb26d290a45e Mon Sep 17 00:00:00 2001 From: Martial Simon Date: Mon, 15 Sep 2025 01:07:58 +0200 Subject: add: added projects --- 21sh/myredir/myredir.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 21sh/myredir/myredir.c (limited to '21sh/myredir') 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 +#include +#include +#include +#include + +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; + } +} -- cgit v1.2.3