execve and forks ok

This commit is contained in:
Hugo LAMY
2022-06-26 18:03:13 +02:00
parent a035862584
commit 14130caef7
4 changed files with 99 additions and 7 deletions

66
Makefile Normal file
View File

@@ -0,0 +1,66 @@
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# . name = value \ . += append to a variable #
# VARIABLES . value . != set result of command #
# . name is case sensitive . ?= set if not already set #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
NAME = microshell
CC = gcc
EXT = c
CFLAGS = -Wall -Wextra -Werror $(INCLUDES)
VPATH = $(D_SRCS)
LIBS =
INCLUDES = -I$(D_HEADERS)
D_SRCS = .
SRCS = microshell.c
D_HEADERS = .
HEADERS =
D_OBJS = builds
OBJS = $(SRCS:%.$(EXT)=$(D_OBJS)/%.o)
RM_OBJS = rm -rf $(D_OBJS)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# . target: prerequisites . $@ : target #
# RULES . recipe . $< : 1st prerequisite #
# . recipe . $^ : all prerequisites #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
all: $(NAME)
$(D_OBJS)/%.o: %.$(EXT) | $(D_OBJS)
$(CC) $(CFLAGS) -c $< -o $@
$(D_OBJS):
mkdir $@
$(OBJS): $(HEADERS:%=$(D_HEADERS)/%)
$(NAME): $(OBJS)
$(CC) $(OBJS) -o $@ $(LIBS)
leaks: $(NAME)
valgrind --leak-check=full --show-leak-kinds=all ./$(NAME)
test: $(NAME)
./microshell /bin/ls "|" /usr/bin/grep microshell ";" /bin/echo i love my microshell
clean:
$(RM_OBJS)
fclean: clean
rm -f $(NAME)
re: fclean all
.PHONY : all clean fclean re

BIN
builds/microshell.o Normal file

Binary file not shown.

BIN
microshell Executable file

Binary file not shown.

View File

@@ -1,14 +1,20 @@
#include <unistd.h> // write
#include <stdio.h> // printf
#include <string.h> // strcmp
#include <unistd.h> // write, fork, execve, pipe
#include <stdio.h> // printf
#include <string.h> // strcmp
#include <sys/types.h> // pid_t
#include <sys/wait.h> // waitpid
void print_cmd(char **av, int end)
#define STDIN 0
#define STDOUT 1
#define STDERR 2
void print_cmd(char **av)
{
int i;
int size;
i = 0;
while (i < end)
while (av[i])
{
size = 0;
while (av[i][size] != '\0')
@@ -20,7 +26,23 @@ void print_cmd(char **av, int end)
write(1, "\n", 1);
}
int main(int ac, char **av)
//void exec_cmd(char **av, int end, char **en)
void exec_cmd(char **av, char **en)
{
pid_t pid = fork();
// av[end] = NULL;
if (pid == 0) // child process
{
execve(av[0], av, en);
}
else // parent process
{
waitpid(pid, NULL, 0);
}
}
int main(int ac, char **av, char **en)
{
int i;
int start;
@@ -33,9 +55,13 @@ int main(int ac, char **av)
start = i;
while (i < ac && strcmp(av[i], "|") && strcmp(av[i], ";"))
i++;
print_cmd(&av[start], i - start);
av[i] = NULL;
// print_cmd(&av[start]);
exec_cmd(&av[start], en);
if (i < ac)
i++;
}
return (0);
}
// https://www.rozmichelle.com/pipes-forks-dups/