mstagg
mstagg

Reputation: 497

Exiting child process

I have the following code. It consists of a parent process and two child processes (a producer and a consumer). The producer accepts user input and passes it along to the consumer, which sums up the total number of vowels that have occurred. The parent process just listens to the two children processes and restarts them if they have stopped for whatever reason. The producer process exits when the user inputs 'p' and the consumer process stops when it receives a string that contains a 'y'.

The issue I am having is that the _exit() function call in the producer process is not causing the process to terminate. The _exit() function call in the consumer process works as intended. Why is the consumer process terminating correctly while the producer function does not?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

int main(){
    pid_t c_p, c_c;
    int p[2];
    pipe(p);
    c_p = fork(); 
    if(c_p > 0) c_c = fork();

    for(;;){
        // Producer Process
        if(c_p == 0){
            char c[20];
            printf("%s", "Enter a string: \n");
            fgets(c, 20, stdin);
            if(c[0] == 'p' && strlen(c) == 2) _exit(1);
            close(p[0]);
            write(p[1], c, (strlen(c) + 1));
        }

        // Consumer Process
        else if(c_c == 0){
            int j;
            static int a = 0, e = 0, i = 0, o = 0, u = 0;
            char buffer[20];
            close(p[1]);
            read(p[0], buffer, sizeof(buffer));

            for(j = 0; j < strlen(buffer); j++){
                if     (buffer[j] == 'a' || buffer[j] == 'A') a++;
                else if(buffer[j] == 'e' || buffer[j] == 'E') e++;
                else if(buffer[j] == 'i' || buffer[j] == 'I') i++;
                else if(buffer[j] == 'o' || buffer[j] == 'O') o++;
                else if(buffer[j] == 'u' || buffer[j] == 'U') u++;
                else if(buffer[j] == 'y' || buffer[j] == 'Y') _exit(1);
            }

            printf("Sum of Vowels... \tA: %d \tE: %d \tI: %d \tO: %d \tU: %d\n", a, e, i, o, u);
        }

        // Main Process
        else{
            int status;
            pid_t result = waitpid(c_c, &status, WNOHANG);
            if(result > 0){
                c_c = fork();
            }

            /*result = waitpid(c_p, &status, WNOHANG);
            if(result > 0){
                c_p = fork();
            }*/
        }
    }

    return 0;
}

Upvotes: 1

Views: 257

Answers (1)

Marvin Wang
Marvin Wang

Reputation: 207

There are four processes exist in your program after

c_p = fork(); c_c = fork();

You can change it to this:

c_p = fork(); 
if (c_p > 0)
{
    c_c = fork();
    // Do something.
} else if (c_p == 0)
{
    // Do something.
}

Upvotes: 5

Related Questions