summaryrefslogtreecommitdiff
path: root/21sh/mypipe
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/mypipe
add: added projectsHEADmain
Diffstat (limited to '21sh/mypipe')
-rw-r--r--21sh/mypipe/mypipe.c43
-rw-r--r--21sh/mypipe/mypipe.h6
2 files changed, 49 insertions, 0 deletions
diff --git a/21sh/mypipe/mypipe.c b/21sh/mypipe/mypipe.c
new file mode 100644
index 0000000..c019e42
--- /dev/null
+++ b/21sh/mypipe/mypipe.c
@@ -0,0 +1,43 @@
+#include "mypipe.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+
+int exec_pipe(char **argv_left, char **argv_right)
+{
+ int fds[2];
+ if (pipe(fds))
+ return 1;
+ pid_t pid = fork();
+ if (pid == 0)
+ {
+ // close read end
+ close(fds[0]);
+ // redirect stdout to write end
+ dup2(fds[1], STDOUT_FILENO);
+ // tell OS to close write end after exec
+ fcntl(fds[1], F_SETFD, FD_CLOEXEC);
+ // exec left
+ execvp(argv_left[0], argv_left);
+ return 0;
+ }
+ else if (pid > 0)
+ {
+ // close write end
+ close(fds[1]);
+ // redirect stdin to read end
+ dup2(fds[0], STDIN_FILENO);
+ // tell OS to close read end after exec
+ fcntl(fds[0], F_SETFD, FD_CLOEXEC);
+ // exec right
+ execvp(argv_right[0], argv_right);
+ // return 1
+ return 1;
+ }
+ else
+ {
+ close(fds[0]);
+ close(fds[1]);
+ return 1;
+ }
+}
diff --git a/21sh/mypipe/mypipe.h b/21sh/mypipe/mypipe.h
new file mode 100644
index 0000000..d8c14e4
--- /dev/null
+++ b/21sh/mypipe/mypipe.h
@@ -0,0 +1,6 @@
+#ifndef MYPIPE_H
+#define MYPIPE_H
+
+int exec_pipe(char **argv_left, char **argv_right);
+
+#endif /* ! MYPIPE_H */