tgrekov-pipex
HIVE pipex May 2024
Loading...
Searching...
No Matches
dispatch.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* dispatch.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/04/22 13:32:09 by tgrekov #+# #+# */
9/* Updated: 2024/05/20 12:27:21 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include <unistd.h>
21#include <string.h>
22#include <errno.h>
23#include <stdlib.h>
24#include <libft.h>
25#include <ft_printf.h>
26#include "../utils/utils.h"
27
28char **args_split(char const *s);
29char *get_cmd(char **paths, char *name);
30
31static int _dispatch(char **paths, char **argv, char **envp, int *in_out)
32{
33 char *cmd;
34
35 cmd = get_cmd(paths, argv[0]);
36 if (!cmd)
37 {
38 ft_printf("%>Command not found: %s\n", 2, argv[0]);
39 return (127);
40 }
41 if (access(cmd, X_OK))
42 {
43 ft_printf("%>No access to execute \"%s\"\n", 2, cmd);
44 return (126);
45 }
46 if (dup2(in_out[0], 0) == -1)
47 return ((int) err("dup2()", (void *) 1));
48 if (dup2(in_out[1], 1) == -1)
49 return ((int) err("dup2()", (void *) 1));
50 execve(cmd, argv, envp);
51 free(cmd);
52 ft_printf("%>execve() failed for \"%s\": %s\n", 2, cmd, strerror(errno));
53 return (1);
54}
55
67void dispatch(char **paths, char *args, char **envp, int *in_out)
68{
69 char **child_argv;
70 int code;
71
72 if (in_out[0] == -1 || in_out[1] == -1)
73 {
74 arr_free((void **) paths);
75 exit(1);
76 }
77 code = 1;
78 child_argv = ft_split(args, ' ');
79 if (child_argv)
80 {
81 code = _dispatch(paths, child_argv, envp, in_out);
82 arr_free((void **) child_argv);
83 }
84 else
85 ft_printf("%>Could not split arguments \"%s\": %s\n",
86 2, args, strerror(errno));
87 arr_free((void **) paths);
88 exit(code);
89}
void ** arr_free(void **arr)
Free each element in a null-terminated array, and then the array itself.
Definition arr_free.c:29
int ft_printf(const char *format,...)
Prints and formats a variable set of arguments.
Definition ft_printf.c:252
void dispatch(char **paths, char *args, char **envp, int *in_out)
Dispatch child process with argument string args, environment envp, and stdin / stdout in_out[0] / in...
Definition dispatch.c:67
char * get_cmd(char **paths, char *name)
Find and return the first existing file with called name from the array of paths.
Definition get_cmd.c:33
void * err(const char *str, void *retval)
Wrapper around perror() that always returns retval.
Definition err.c:29
char ** ft_split(char const *s, char c)
Split string s by characer c into allocated array of strings, with NULL as the last element.
Definition ft_split.c:72