المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Two way communication between parent and child processes...



C++ Programming
05-05-2010, 02:12 AM
Good afternoon!

Taking the following into account:


/**************************************************************
* 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 #include #include
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 forums such as this one. Any and all suggestions are welcome!