Two way communication between parent and child processes...

This is a discussion on Two way communication between parent and child processes... within the C Programming forums, part of the General Programming Boards category; Good afternoon! Taking the following into account: Code: /************************************************************** * p2cComm.c * * C program that implements communication between two ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    7

    Two way communication between parent and child processes...

    Good afternoon!

    Taking the following into account:

    Code:
    /**************************************************************
    * p2cComm.c
    *   
    * C program that implements communication between two processes  
    * Program creates 2 unnamed pipes, p and q. Then it creates a 
    * child process. Next, it links the parent with the child using
    * the two pipes. Pipe p: Parent to Child, Pipe q: Child to Parent.
    * Child receives commands from parent through Pipe p and sends 
    * responses through Pipe q.
    ***************************************************************/  
    
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <unistd.h> 
     
    int main(int argc, char *argv[]){ 
     
            int pid; 
            int p[2];   /* pipe "p" */ 
            int q[2];   /* pipe "q" */ 
            int a; 
            int b; 
     
            /* Create Pipe. Pipe P is used to transfer information  
            from the parent process to the child process */ 
            a = pipe(p);
            if(a == -1) 
            { 
            fprintf(stderr, "Pipe Failed.\n"); 
            return EXIT_FAILURE; 
            } 
             
            /* Create second pipe. Pipe Q is used to transfer information 
            from the child process to the parent process. */ 
            b = pipe(q); 
            if(b == -1) 
            { 
             fprintf(stderr, "Pipe Failed.\n"); 
             return EXIT_FAILURE; 
            } 
             
            /* Create child process */ 
            pid = fork(); 
     
            switch(pid){ 
             
                    case -1: /* fork failed */ 
                            perror("main: fork"); 
                            exit(1); 
                    
    		/* Child process will execute a loop, waiting for command
    		from the parent process. Child executes the command. Child
    		returns a response to the parent */
    		case 0: /* Child process */ 
                    printf("Child process ID: %d\n", pid);
                    break;
                    /* do some things */ 
     
                    /* Parent process will execute a loop, asking user for a one
    		line command. Parent sends command to child for execution.
    		Parent waits for the response of the child. Parent finally
    		reports the result (displayed on screen). */
    		default: /* Parent process */ 
                    printf("Parent process ID: %d\n", pid);
                    break;
                    /* do some things */ 
             } 
            getchar();
            return 0; 
    }

    The child program will execute a list of commands that it receives from the parent (via pipe p). I have a menu of commands that will run in the parent process and send the user's choice to the child for execution. The child will send the results back to the parent when done (through pipe q), so the parent process may display the results.

    In the code sample I submitted, I've created both pipes, p and q. Then, I forked the child process. My question is how will the child know to recieve it's commnads through pipe p and how will the parent know to receive the results through pipe q? Should the creation of the second pipe occur later in the code than where it is located?

    As always, I greatly appreciate the guidence that I have recieved while visiting this forum. Any and all suggestions are welcome!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,751
    It doesn't matter, both have a read end and a write end.

    If the parent writes p[1], then the child reads p[0] - it's that simple.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    7
    Okay, I'm back. I tried something different. But it's not performing properly...

    Code:
    //Uses two pipes to establish 2-way communication
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <ctype.h>
    
    #define MAXLINE 4096
    
        char command[MAXLINE];
        char choice1[] = "display";
        char choice2[] = "chars";
        char choice3[] = "lines";
        char choice4[] = "words";
        char choice5[] = "find";
        char choice6[] = "exit";
        char filename[50] = "";
        char line[255];
        char x;
        int ch, c;
        int count = 0;
        int words = 0;
        int l = 0;
        FILE *fp;
        FILE *in_file;
        FILE *pFile;
        FILE *wordcount;
    
    int main(void){
    
    	int pid;	//allows parent and child to identify themselves
    	int p[2];	//Pipe 'p'
    	int q[2];	//Pipe 'q'
    	
    	//create 2 pipes
    	if (pipe(p) < 0 || pipe(q) < 0){
    	puts("Cannot create pipe");
    	exit(0);
    	} // end if pipe fails
    	
    	pid = fork(); 
    	
    	if (pid > 0){ //in parent process
    	close (p[0]);
    	close (q[1]);
    	
    	menu(q[0], p[1]);
    	
    	close (p[1]);
    	close(q[0]);
    	exit(0);	
    	} //end if in parent
    	
    	else{ //in child
    	close (p[1]);
    	close (q[0]);
    
    	execution(p[0], q[1]);
    	
    	close (p[0]);
    	close (q[1]);
    	exit(0);
    	} //end if in child
    }  // end main program
    
    
    int menu (int argc, char *argv[]){
    
        printf("------------------------------------------\n");
        printf("Please choose from the following commands:\n\n");
        printf("display\n");
        printf("chars\n");
        printf("lines\n");
        printf("words\n");
        printf("find\n");
        printf("exit\n\n");
        printf("------------------------------------------\n");
        
        printf("Please enter a command: ");
        scanf("%s" "%s", command, filename);
        
        printf("\n\nThe command is: %s %s\n\n", command, filename);
    
        return(0);
    }
    
    int execution (int argc, char *argv[]){
    
    if(strcmp(choice1, command) == 0){
        
           printf("Executing command: %s %s\n\n", command, filename);
           printf("=================\n");
           printf("\nFile contents are: \n\n %s\n", filename);
           
           fp = fopen(filename, "r");
           if((fp == NULL))
           {       
           printf("No file was selected!\n");
           exit(1);       
           }
           while(!feof(fp))
            {
            if(fgets(line, 255, fp))
            printf("%s", line);               
            }
            printf("\n\nEnd of file: \n\n");
            printf("================\n\n");
            printf("The command was executed\n\n");
            printf("The file was displayed\n\n");
            
            fclose(fp);    
            }
        else if(strcmp(choice2, command) == 0){
                   
            printf("Executing command: %s %s\n\n", command, filename);
            in_file = fopen(filename, "r");
                    if(in_file == NULL){
                         printf("Cannot open %s\n", filename);
                         exit(8);
                    }
                    while(1){
                         ch = fgetc(in_file);
                         if(ch == EOF)
                           break;
                         ++count;
                    }
                    printf("\nNumber of characters in %s is %d\n\n\n", filename, count);
                    fclose(in_file);
             printf("The command was executed\n\n");
             printf("The file was displayed\n\n");
                   
                   }
        else if(strcmp(choice3, command) == 0){
             printf("Executing command: %s \n\n", command);
             pFile = fopen(filename, "r");
             if(pFile == NULL)perror("Error openning file");
             else{
                  do{
                     c = fgetc(pFile);
                     if(c == '\n') l++;
                  }
                  while(c != EOF);
               printf("File contains %d lines\n\n", l);
               fclose(pFile);
                    }
                   }
                   return 0;
    }
    It compiles okay in Dev-C++. I upload to my UNIX server and compile it there using gcc. It compiles with no errors. When I run it, the menu comes up and I can type in a command from the list. It displays the name of the command and the file and then nothing else. It does not go to the other function called execution and do the work.

    What am I doing wrong?

    Thanks!

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Why are you trying to pass an int and an int to functions with arguments int and char*[]? And since you don't use those arguments in any way.... (Just passing a pipe to a function does not magically mean the function will use that pipe.)

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,751
    How about a simpler test program?

    Parent sends "hello"
    Child receives "hello" and prints it
    Child sends "bye" (and exits)
    Parent receives "bye" and prints it.

    > while(!feof(fp))
    There's a FAQ about this.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    May 2011
    Posts
    1
    Have similar problem as the one above? Did anyone ever figure out why the execution does not run? I even took out the arguments being passed to it. It still doesnt work.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,751
    Post your latest effort in a new thread.
    As opposed to bumping an old thread with "it doesn't work".
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 11:09 AM
  2. Trouble understanding parent and child processes
    By cardinals03 in forum C++ Programming
    Replies: 11
    Last Post: 10-04-2009, 06:51 PM
  3. Replies: 3
    Last Post: 10-15-2008, 10:24 AM
  4. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 08:53 AM
  5. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 10:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21