aboutsummaryrefslogtreecommitdiff
path: root/src/execute_cmd.c
diff options
context:
space:
mode:
authorChristopher Uhlig2025-01-13 11:06:54 +0100
committerChristopher Uhlig2025-01-13 11:06:54 +0100
commit78dc50a2bce3c6e31405437189e2990d8fc720ac (patch)
treed61d9f0d279e191c1bfb34929908f412cf58c02d /src/execute_cmd.c
parentae5512ea0d6d8be833ca3a9b39f93239109f45b4 (diff)
downloadminishell-78dc50a2bce3c6e31405437189e2990d8fc720ac.tar.gz
minishell-78dc50a2bce3c6e31405437189e2990d8fc720ac.zip
here
Diffstat (limited to 'src/execute_cmd.c')
-rw-r--r--src/execute_cmd.c77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/execute_cmd.c b/src/execute_cmd.c
new file mode 100644
index 0000000..803d88f
--- /dev/null
+++ b/src/execute_cmd.c
@@ -0,0 +1,77 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* execute_cmd.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: chuhlig <chuhlig@student.42.fr> +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2024/12/17 19:21:35 by chuhlig #+# #+# */
+/* Updated: 2025/01/13 09:50:56 by chuhlig ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "minishell.h"
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/_types/_pid_t.h>
+#include <sys/_types/_s_ifmt.h>
+#include <sys/fcntl.h>
+#include <unistd.h>
+
+int execute_cmd(t_cmd *cmd, t_env **env)
+{
+ char *cmd_path;
+ pid_t pid;
+ int status;
+ int result;
+ int original_stdout;
+ int original_stdin;
+
+ original_stdout = dup(STDOUT_FILENO);
+ original_stdin = dup(STDIN_FILENO);
+ if (handle_redirections(cmd->redirs) == -1)
+ {
+ dup2(original_stdout, STDOUT_FILENO);
+ dup2(original_stdin, STDIN_FILENO);
+ close(original_stdout);
+ close(original_stdin);
+ return (EXIT_FAILURE);
+ }
+ if (is_builtin(cmd->args[0]))
+ {
+ result = execute_builtin(cmd->args, env);
+ dup2(original_stdout, STDOUT_FILENO);
+ dup2(original_stdin, STDIN_FILENO);
+ close(original_stdout);
+ close(original_stdin);
+ return (result);
+ }
+ pid = fork();
+ if (pid == -1)
+ {
+ perror("fork");
+ dup2(original_stdout, STDOUT_FILENO);
+ dup2(original_stdin, STDIN_FILENO);
+ close(original_stdout);
+ close(original_stdin);
+ return (EXIT_FAILURE);
+ }
+ if (pid == 0)
+ {
+ cmd_path = get_cmd_path(cmd->args[0], *env);
+ if (!cmd_path)
+ {
+ printf("%s: command not found\n", cmd->args[0]);
+ exit(EXIT_FAILURE);
+ }
+ execve(cmd_path, cmd->args, env_to_strlst(*env));
+ perror("execve");
+ exit(EXIT_FAILURE);
+ }
+ waitpid(pid, &status, 0);
+ dup2(original_stdout, STDOUT_FILENO);
+ dup2(original_stdin, STDIN_FILENO);
+ close(original_stdout);
+ close(original_stdin);
+ return (WEXITSTATUS(status));
+} \ No newline at end of file