From 0a5684e637cd6ec084575ddf9930cfde55d3cca7 Mon Sep 17 00:00:00 2001 From: Dominik Kaiser Date: Tue, 22 Oct 2024 15:42:28 +0200 Subject: [PATCH] Add pipe basics TODO: Add actual piping --- src/execute_cmd.c | 21 +++---------- src/interpreter.c | 79 +++++++++++++++++++++++++++++++---------------- 2 files changed, 58 insertions(+), 42 deletions(-) diff --git a/src/execute_cmd.c b/src/execute_cmd.c index 3730d4b..33ba11c 100644 --- a/src/execute_cmd.c +++ b/src/execute_cmd.c @@ -6,7 +6,7 @@ /* By: dkaiser args[0], cmd->args, env_to_strlst(env)); - exit(result); - } - else - { - // only wait if cmd is on rightmost side of pipe? - // so in cmd1 | cmd2 | cmd3 | cmd4 only wait for cmd4 - waitpid(pid, &result, 0); - } + cmd_path = get_cmd_path(cmd->args[0], env); + cmd->args[0] = cmd_path; + result = execve(cmd->args[0], cmd->args, env_to_strlst(env)); return (result); } diff --git a/src/interpreter.c b/src/interpreter.c index 1082644..f6757c4 100644 --- a/src/interpreter.c +++ b/src/interpreter.c @@ -6,46 +6,73 @@ /* By: dkaiser +#include +#include #include +#include -static int eval_pipe(t_pipe *pipe, t_env *env); -static int eval_cmd(t_cmd *cmd, t_env *env); +int eval_rec(t_node *node, t_env *env); int eval(t_node *node, t_env *env) { - if (node->type == PIPE_NODE) - return (eval_pipe(&node->content.pipe, env)); - else if (node->type == CMD_NODE) - return (eval_cmd(&node->content.cmd, env)); + pid_t pid; + int result; + + result = 0; + pid = fork(); + if (pid < 0) + { + return (EXIT_FAILURE); + } + if (pid == 0) + { + result = eval_rec(node, env); + exit(result); + } else { - panic(UNREACHABLE); - return (-1); + waitpid(pid, &result, 0); } + return (result); } -static int eval_pipe(t_pipe *pipe, t_env *env) -{ - dbg("TODO: PIPE"); - eval_cmd(&pipe->left->content.cmd, env); - eval_cmd(&pipe->right->content.cmd, env); - return (0); -} - -static int eval_cmd(t_cmd *cmd, t_env *env) +int eval_rec(t_node *node, t_env *env) { - char *cmd_path; + pid_t pid; + int result; - cmd_path = get_cmd_path(cmd->args[0], env); - if (cmd_path == NULL) - return (1); - free(cmd->args[0]); - cmd->args[0] = cmd_path; - execute_cmd(cmd, env); - return (0); + if (node->type == PIPE_NODE) + { + pid = fork(); + if (pid < 0) + { + return (EXIT_FAILURE); + } + if (pid == 0) + { + result = execute_cmd(&node->content.pipe.left->content.cmd, env); + exit(result); + } + else + { + result = eval(node->content.pipe.right, env); + } + } + else if (node->type == CMD_NODE) + { + result = execute_cmd(&node->content.cmd, env); + } + else + { + panic(UNREACHABLE); + return (EXIT_FAILURE); + } + return (result); } -- 2.47.2