CS3413/Assignment2/main.c

87 lines
2.5 KiB
C
Raw Normal View History

2023-09-26 11:27:36 -03:00
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdbool.h>
2023-09-26 14:23:21 -03:00
#include <stdlib.h>
#include <wait.h>
void print_prompt() {
printf("[%d]> ", getpid());
}
2023-09-26 11:27:36 -03:00
int main() {
bool is_looping = true;
// Listen loop
while (is_looping) {
2023-09-26 14:23:21 -03:00
char input[100];
print_prompt();
fgets(input, 100, stdin);
if (strcmp(input, "stop\n") == 0) {
is_looping = false;
}
if (strcmp(input, "onechild\n") == 0) {
if(fork() == 0) {
print_prompt();
printf("Hello, I am a child process\n");
exit(0);
}
else {
print_prompt();
printf("Hello, I am a parent process\n");
wait(NULL);
}
2023-09-26 11:27:36 -03:00
}
2023-09-26 14:23:21 -03:00
if (strcmp(input, "addnumbers\n") == 0) {
int number = 1;
int send_to_child[2];
int receive_from_child[2];
pipe(send_to_child);
pipe(receive_from_child);
2023-09-26 11:27:36 -03:00
2023-09-26 14:23:21 -03:00
if (fork() == 0) {
2023-09-26 14:41:29 -03:00
int subtotal = 0;
2023-09-26 14:23:21 -03:00
while (number != 0) {
// Read the numbers from the send_to_child pipe
read(send_to_child[0], &number, sizeof(int));
2023-09-26 14:41:29 -03:00
subtotal += number;
2023-09-26 14:23:21 -03:00
print_prompt();
2023-09-26 14:41:29 -03:00
printf("The subtotal is %d\n", subtotal);
2023-09-26 14:23:21 -03:00
// Write the sum to the receive_from_child pipe
2023-09-26 14:41:29 -03:00
write(receive_from_child[1], &subtotal, sizeof(int));
2023-09-26 14:23:21 -03:00
}
exit(0);
}
else {
2023-09-26 14:41:29 -03:00
int total = 0;
2023-09-26 14:23:21 -03:00
while (number != 0) {
print_prompt();
printf("Please input a number, 0 to terminate: ");
char buffer[100];
fgets(buffer, 100, stdin);
number = atoi(buffer);
2023-09-26 14:41:29 -03:00
print_prompt();
printf("You entered %d\n", number);
2023-09-26 14:23:21 -03:00
write(send_to_child[1], &number, sizeof(int));
2023-09-26 14:41:29 -03:00
read(receive_from_child[0], &total, sizeof(int));
2023-09-26 14:23:21 -03:00
}
2023-09-26 14:41:29 -03:00
print_prompt();
printf("The total is %d\n", total);
2023-09-26 14:23:21 -03:00
}
2023-09-26 11:27:36 -03:00
}
}
}
2023-09-26 14:23:21 -03:00
void temp() {
char input[5][100];
char buffer[500];
//Print prompt
print_prompt();
if (fgets(buffer, 500, stdin) == NULL) {
exit(0);
}
//split buffer on spaces into input array
sscanf(buffer, "%s %s %s %s %s", input[0], input[1], input[2], input[3], input[4]);
};