Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* ************************************************************************** */
- /* */
- /* ::: :::::::: */
- /* microshell.c :+: :+: :+: */
- /* +:+ +:+ +:+ */
- /* By: lduplain <[email protected]> +#+ +:+ +#+ */
- /* +#+#+#+#+#+ +#+ */
- /* Created: 2021/01/09 15:59:05 by gbaud #+# #+# */
- /* Updated: 2022/03/01 14:54:35 by lduplain ### ########.fr */
- /* */
- /* ************************************************************************** */
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #define ERR_FATAL "error: fatal\n"
- #define ERR_EXEC "error: cannot execute "
- #define ERR_CD_ARG "error: cd: bad arguments\n"
- #define ERR_CD_DIR "error: cd: cannot change directory to "
- int ft_strlen(char *str)
- {
- int index;
- index = 0;
- while (str[index])
- index++;
- return (index);
- }
- int put_err(char *err, char *path)
- {
- write(2, err, ft_strlen(err));
- if (path != NULL)
- {
- write(2, path, ft_strlen(path));
- write(2, "\n", 1);
- }
- return (1);
- }
- void sub(char **cmds, char **av, int from, int to)
- {
- int cmd_arg_index;
- cmd_arg_index = 0;
- while (from < to)
- cmds[cmd_arg_index++] = av[from++];
- cmds[cmd_arg_index] = NULL;
- }
- int cd(char **av, int len)
- {
- if (len != 2)
- return (put_err(ERR_CD_ARG, NULL));
- if (chdir(av[1]))
- return (put_err(ERR_CD_DIR, av[1]));
- return (0);
- }
- int main(int argc, char **argv, char **env)
- {
- int arg_index;
- int next_semi;
- int cmd_index;
- int next_pipe;
- int pipefd[2];
- pid_t pid;
- int fd_in;
- arg_index = 1;
- while (arg_index < argc)
- {
- next_semi = arg_index;
- while (next_semi < argc && strncmp(argv[next_semi], ";", 2) != 0)
- next_semi++;
- fd_in = 0;
- cmd_index = arg_index;
- while (cmd_index < next_semi)
- {
- next_pipe = cmd_index;
- while (next_pipe < next_semi && strncmp(argv[next_pipe], "|", 2) != 0)
- next_pipe++;
- char *cmds[next_pipe - cmd_index + 1];
- sub(cmds, argv, cmd_index, next_pipe);
- pipe(pipefd);
- if ((pid = fork()) == -1)
- return (put_err(ERR_FATAL, NULL));
- else if (pid == 0)
- {
- dup2(fd_in, 0);
- if (next_pipe < next_semi)
- dup2(pipefd[1], 1);
- close(pipefd[0]);
- if (strncmp(cmds[0], "cd", 3) == 0)
- cd(cmds, next_pipe - cmd_index);
- else if (execve(cmds[0], cmds, env) == -1)
- {
- close(pipefd[1]);
- close(fd_in);
- return (put_err(ERR_EXEC, cmds[0]));
- }
- close(pipefd[1]);
- close(fd_in);
- return (0);
- }
- else
- {
- waitpid(pid, NULL, 0);
- close(pipefd[1]);
- if (fd_in)
- close(fd_in);
- fd_in = pipefd[0];
- }
- cmd_index = next_pipe + 1;
- }
- close(fd_in);
- arg_index = next_semi + 1;
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment