summaryrefslogtreecommitdiff
path: root/21sh/myredir/myredir.c
diff options
context:
space:
mode:
authorMartial Simon <msimon_fr@hotmail.com>2025-09-15 01:07:58 +0200
committerMartial Simon <msimon_fr@hotmail.com>2025-09-15 01:07:58 +0200
commit967be9e750221ab2ab783f95df79bb26d290a45e (patch)
tree6802900a5e975f9f68b169f0f503f040056d6952 /21sh/myredir/myredir.c
add: added projectsHEADmain
Diffstat (limited to '21sh/myredir/myredir.c')
-rw-r--r--21sh/myredir/myredir.c46
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;
+ }
+}