I have (in main()) something like:
int toChild[2], fromChild[2];
pid_t pid;
//Creating pipes:
if(pipe(toChild) != 0){
return 1;
}
if(pipe(fromChild) != 0){
return 1;
}
//Forking:
if((pid = fork()) == -1)
return 1;
if(pid == 0)
{/* CHILD */
close(toChild[1]);
close(fromChild[0]);
//create streams: (they are not used in this example)
FILE *toChildStream;
FILE *fromChildStream;
if ((toChildStream = fdopen(toChild[0], "r")) == NULL)
return 1; //error: could not create stream
if ((fromChildStream = fdopen(fromChild[1], "w")) == NULL)
return 1; //error: could not create stream
puts(">In Child");
return 0;
}
else
{/* PARENT */
close(toChild[0]);
close(fromChild[1]);
//create streams:
FILE *toChildStream;
FILE *fromChildStream;
if ((toChildStream = fdopen(toChild[1], "w")) == NULL)
return 1; //error: could not create stream
if ((fromChildStream = fdopen(fromChild[0], "r")) == NULL)
return 1; //error: could not create stream
puts(">Parent1");
fputs(">Some text", toChildStream); //parent writes to child
puts(">Parent2");
}
char* i;
printf(">End");
scanf(i);
return 0;
But here is a problem: when executed this code outputs:
>Parent1 >In Child
>Parent2
>End
or
>Parent1
>Parent2
>End >In Child
Sometimes " >In Child
" is even in different places.
This is just an example, but you should get the idea.
I would like to create two pipes (from and to child process) and be able to communicate between them. Is there anything I can do to determine if the child process is now active or waits for data from parent etc.; What is the cause of above weird results and how to avoid it?
Thanks in adv.