Search code examples
cpipeparent-childinterprocess

Inter-process communication seems to be hanging


This is a program that was designed to take characters from the program call, pipe them one at a time to a child, count them in the child, return that value to the parent and print that value. For some reason, the number of characters input isn't being displayed. It compiles without error and runs, but doesn't exit properly. This leads me to believe that the parent doesn't successfully reap the child and take the return value from it.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>


int main(int argc, char **argv)
{
    int comm[2];
    char buffer[50];
    pid_t   pid;

    // set up pipe

    pipe(comm);

    // call fork()
    pid = fork();

    // code that runs in the child  
    if (pid == 0) {
        // -- running in child process --
        int     nChars = 0;

        close(comm[1]);

        // Receive characters from parent process via pipe
        // one at a time, and count them.

        while(read(comm[0], buffer, 1) ==1) {
            ++nChars;
        }

        // Return number of characters counted to parent process.
        return nChars;
    }
    else {
        // -- running in parent process --
        int     nChars = 0;
        int     size = 0;
        printf("CS201 - Assignment 3 - \n");

        // Send characters from command line arguments starting with
        // argv[1] one at a time through pipe to child process.
        close(comm[0]);
        for (int i = 1; i < argc ; i++) {
            size = strlen(argv[i]);
            for (int j = 0; j < size; j++) {
            write(comm[1], &argv[i][j], 1);
                }
            }

        // Wait for child process to return. Reap child process.
        // Receive number of characters counted via the value
        // returned when the child process is reaped.

        wait(&nChars);
        printf("child counted %d chars\n", nChars/256);
        return 0;
        }
}

Solution

  • Your parent process needs to close the pipe after it's done writing.

    // Send characters from command line arguments starting with
    // argv[1] one at a time through pipe to child process.
    close(comm[0]);
    for (int i = 1; i < argc ; i++) {
        size = strlen(argv[i]);
        for (int j = 0; j < size; j++) {
            write(comm[1], &argv[i][j], 1);
        }
    }
    close(comm[1]); // <--- add this