Skip to content
Snippets Groups Projects
Commit 9364d082 authored by iliya's avatar iliya
Browse files

feat: ex1 pipes done

parent 65df02fc
Branches
No related tags found
No related merge requests found
*.o
simple_pipe
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
#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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment