add: assigment 2
This commit is contained in:
parent
3a0b8a5c3f
commit
32a6e07e56
11 changed files with 437 additions and 0 deletions
56
assignment2/part2/bidirectional.c
Normal file
56
assignment2/part2/bidirectional.c
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
int main () {
|
||||
int pipe1[2]; // Parent to child
|
||||
int pipe2[2]; // Child to parent
|
||||
|
||||
// Create both pipes
|
||||
if (pipe(pipe1) == -1 || pipe(pipe2) == -1) {
|
||||
fprintf(stderr, "Could not open pipes");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Fork process
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid == 0) {
|
||||
// Child process
|
||||
|
||||
// Close unused pipe ends
|
||||
close(pipe1[1]) ; // Close write end of pipe1
|
||||
close(pipe2[0]) ; // Close read end of pipe2
|
||||
|
||||
// Read message, send response
|
||||
char *message = malloc(100);
|
||||
read(pipe1[0], message, 100);
|
||||
printf("%s", message);
|
||||
free(message);
|
||||
|
||||
char response[] = "Response from child to parent\n";
|
||||
write(pipe2[1], response, sizeof(response));
|
||||
} else {
|
||||
// Parent process
|
||||
|
||||
// Close unused pipe ends
|
||||
close(pipe1[0]) ; // Close read end of pipe1
|
||||
close(pipe2[1]) ; // Close write end of pipe2
|
||||
|
||||
// Send message, read response
|
||||
char message[] = "Sending message from parent to child\n";
|
||||
write(pipe1[1], message, sizeof(message));
|
||||
|
||||
char *response = malloc(100);
|
||||
read(pipe2[0], response, 100);
|
||||
printf("%s", response);
|
||||
free(response);
|
||||
|
||||
// Wait for child process to terminate
|
||||
waitpid(pid, NULL, 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
assignment2/part2/test
Executable file
20
assignment2/part2/test
Executable file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
echo "Building executable..."
|
||||
|
||||
cd "${FLAKE:-$(dirname $0)}"
|
||||
if command -v nix; then
|
||||
bidirectional="$(nix build --no-link --print-out-paths .#a2-p2-bidirectional)/bin/bidirectional"
|
||||
else
|
||||
gcc bidirectional.c -o bidirectional
|
||||
bidirectional="./bidirectional"
|
||||
fi
|
||||
|
||||
out="$("$bidirectional")"
|
||||
read -r -d '' expected <<EOF
|
||||
Sending message from parent to child
|
||||
Response from child to parent
|
||||
EOF
|
||||
if test "$out" = "$expected"; then
|
||||
echo "SUCCESS"
|
||||
fi
|
||||
Loading…
Add table
Add a link
Reference in a new issue