Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #define F "error: fatal"
- #define BAD "error: cd: bad arguments"
- #define DIR "error: cd: cannot change directory to "
- #define EXE "error: cannot execute "
- typedef struct s_list
- {
- char **av;
- int pipe_fd[2];
- int prev_pipe;
- int prev_type;
- int type; } t_list;
- int ft_strlen(char *s)
- {
- int i = 0;
- while (s && s[i])
- i++;
- return (i);
- }
- void msg(char *str, t_list *list, int k, int f)
- {
- write(2, str, ft_strlen(str));
- if (k)
- write(2, list->av[0], ft_strlen(list->av[0]));
- write(2, "\n", 1);
- if (f)
- exit(1);
- }
- int init_list(t_list *list, char **av, int i)
- {
- int end = i;
- while (av[end] && strcmp(av[end], "|") != 0 && strcmp(av[end], ";") != 0)
- end++;
- if ((end - i) > 0)
- {
- list->av = &av[i];
- list->prev_type = list->type;
- if (!av[end])
- list->type = 0;
- else if
- (strcmp(av[end], "|") == 0) list->type = 1;
- else
- list->type = 2;
- av[end] = NULL;
- list->prev_pipe = list->pipe_fd[0];
- }
- return (end);
- }
- void fork_process(t_list *list, char **env)
- {
- if (list->type == 1 && (dup2(list->pipe_fd[1], 1) < 0))
- msg(F, list, 0, 1);
- if (list->prev_type == 1 && (dup2(list->prev_pipe, 0) < 0))
- msg(F, list, 0, 1);
- if (execve(list->av[0], list->av, env) < 0)
- msg(EXE, list, 1, 1);
- //exit(0); Если не примет, то добавить
- }
- void exe(t_list *list, char **env)
- {
- pid_t pid;
- if ((list->type == 1 || list->prev_type == 1) && pipe(list->pipe_fd))
- msg(F, list, 0, 1);
- if ((pid = fork()) < 0)
- msg(F, list, 0, 1);
- if (!pid)
- fork_process(list, env);
- else
- {
- waitpid(pid, NULL, 0);
- if (list->type == 1 || list->prev_type == 1)
- close(list->pipe_fd[1]);
- if (list->type != 1)
- close(list->pipe_fd[0]);
- if (list->prev_type == 1)
- close(list->prev_pipe);
- }
- }
- int main(int argc, char **argv, char **env)
- {
- t_list list;
- int start, i = 0;
- while (i < argc && argv[++i])
- {
- start = i;
- i = init_list(&list, argv, i);
- if (strcmp(argv[start], "cd") == 0)
- {
- if (i - start != 2)
- msg(BAD, &list, 0, 0);
- else if (chdir(list.av[1]) < 0)
- msg(DIR, &list, 1, 0);
- }
- else if (i > start)
- exe(&list, env);
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement