diff --git a/pipes/ex1/.gitignore b/pipes/ex1/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1b3c3e74e98042cfe44fc4ad36daa467eeb67230 --- /dev/null +++ b/pipes/ex1/.gitignore @@ -0,0 +1,2 @@ +*.o +simple_pipe diff --git a/pipes/ex1/Makefile b/pipes/ex1/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..adf3c701e4a03d08dfd7267a4224700eb6194907 --- /dev/null +++ b/pipes/ex1/Makefile @@ -0,0 +1,26 @@ +CC := clang +CFLAGS := -g -pedantic -Wall -Wextra -std=c11 +LDFLAGS := -fsanitize=address -fsanitize=leak -fsanitize=undefined -lm -lpthread +TARGET := simple_pipe + +all: $(TARGET) + +$(TARGET): simple_pipe.o + @printf "=================== Building executable ===================\n" + $(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS) + @printf "\n" + +%.o: %.c + @printf "================== Building object files ==================\n" + $(CC) $(CFLAGS) -c $< + @printf "\n" + + +.PHONY: clean + +clean: + rm -f *.o $(TARGET) + +.PHONY: rebuild + +rebuild: clean all diff --git a/pipes/ex1/simple_pipe.c b/pipes/ex1/simple_pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..192d0a768211c86ec922ff486171e30858725c67 --- /dev/null +++ b/pipes/ex1/simple_pipe.c @@ -0,0 +1,59 @@ +#include <libgen.h> +#include <stddef.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <time.h> +#include <unistd.h> +#define DATA_LEN (1 << 9) + +int main(void) { + srand(time(NULL)); + + int arr_fd[2] = {0}; + char buff[DATA_LEN] = {0}; + int wstatus; + + for (size_t i = 0; i < DATA_LEN; i++) { + buff[i] = rand() % INT8_MAX; + fprintf(stdout, "%d ", buff[i]); + } + fprintf(stdout, "\n"); + + if (pipe(arr_fd) == -1) { + perror("pipe"); + } + + pid_t pid = fork(); + + if (pid > 0) { // Parent + // Parent closes exit FD + close(arr_fd[0]); + + write(arr_fd[1], buff, DATA_LEN); + close(arr_fd[1]); + + wait(&wstatus); + if (WIFEXITED(wstatus)) { + fprintf(stdout, "Child has terminated\n"); + } + } else if (pid == 0) { // Child + // Child closes entry FD + close(arr_fd[1]); + char child_buff[DATA_LEN] = {0}; + size_t count = 0; + size_t bytes_read = 0; + + while ((bytes_read = read(arr_fd[0], child_buff, 16))) { + count += bytes_read; + } + + fprintf(stdout, "Number of bytes read: %lu\n", count); + } else { // Error + perror("fork"); + } + + return EXIT_SUCCESS; +}