parent process, and a child process..

Posted by icelated on Stack Overflow See other posts from Stack Overflow or by icelated
Published on 2010-03-13T20:57:08Z Indexed on 2010/03/14 1:15 UTC
Read the original article Hit count: 325

Filed under:

I am trying to write a program that The parent process will take the arguments to main() and send the characters in them one at a time to the child process through a pipe (one call to write for each character). The child process will count the characters sent to it by the parent process and print out the number of characters it received from the parent. The child process should not use the arguments to main() in any way whatsoever. The child should return normally and not have the parent kill the child.

Am i counting the arguments right? am i sending the arguments in one at a time, and am i reaping the child?

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define size = 100;

int main(int argc, char *argv[])
{

    int i, count =0;
    int c;

    int     fdest[2];          // for pipe
    pid_t   pid;              //process IDs
    char    buffer[BUFSIZ];



    if (pipe(fdest) < 0)          /* attempt to create pipe */
        perror( "pipe" );

    if ((pid = fork()) < 0)  /* attempt to create child / parent process */

    {
        perror( "fork" );
    } 


    /* parent process */
    else if (pid > 0) { 

        close(fdest[0]);
        for (i=1; i < argc; ++i) 
        {
            for (c=0; c < strlen(argv[i]); ++c) {
                write(fdest[1], &argv[i][c], 1);
            }
        }

        close(fdest[1]);         
        wait(NULL);             
        exit(0);

    } else {   

        /* child Process */
        close(fdest[1]);

        while (read(fdest[0], &buffer, 1) > 0)
        {
            count++;
        }


        printf("\nchild: counted %d characters\n", count);

    }
    wait(NULL);
    exit(0);

}

© Stack Overflow or respective owner

Related posts about c