diff --git a/Assignment2/main.c b/Assignment2/main.c index 5e969eb..8b30957 100644 --- a/Assignment2/main.c +++ b/Assignment2/main.c @@ -16,23 +16,22 @@ int main() { while (is_looping) { char input[100]; print_prompt(); - fgets(input, 100, stdin); - if (strcmp(input, "stop\n") == 0) { + fgets(input, 100, stdin); // Input for commands + if (strcmp(input, "stop\n") == 0) { // Stop command is_looping = false; } - if (strcmp(input, "onechild\n") == 0) { - if(fork() == 0) { + if (strcmp(input, "onechild\n") == 0) { // One child command + if (fork() == 0) { // Child process print_prompt(); printf("Hello, I am a child process\n"); exit(0); - } - else { + } else { // Parent process print_prompt(); printf("Hello, I am a parent process\n"); wait(NULL); } } - if (strcmp(input, "addnumbers\n") == 0) { + if (strcmp(input, "addnumbers\n") == 0) { // Add numbers command int number = 1; int send_to_child[2]; int receive_from_child[2]; @@ -44,26 +43,34 @@ int main() { while (number != 0) { // Read the numbers from the send_to_child pipe read(send_to_child[0], &number, sizeof(int)); + // Add the number to the subtotal subtotal += number; + print_prompt(); printf("The subtotal is %d\n", subtotal); + // Write the sum to the receive_from_child pipe write(receive_from_child[1], &subtotal, sizeof(int)); } exit(0); - } - else { + } else { int total = 0; while (number != 0) { - print_prompt(); printf("Please input a number, 0 to terminate: "); + // Read the number from the user, and convert it to an int char buffer[100]; fgets(buffer, 100, stdin); number = atoi(buffer); + + // Display what was entered print_prompt(); printf("You entered %d\n", number); + + // Write to child process write(send_to_child[1], &number, sizeof(int)); + + // Read the total from the child process read(receive_from_child[0], &total, sizeof(int)); } print_prompt();