thanx for help
the code should be
Code:
#include<stdio.h>
#include<string.h>
int main (void)
{
int fd[2],nbytes,i;
int childpid;
char *f1[5]={"a","b","c","d","e"};
char f2[2];
pipe(fd);
childpid=fork();
if(childpid==0)//start child process
{
for(i=0;i<5;i++)
{
printf("child will print the %dth character and send it to parent\n",i);
printf("%s : from child .. waiting for parent to print same character\n",f1[i]);
close(fd[0]);
write(fd[1],f1[i],(strlen(f1[i])+1));
}
exit(0);
}
else
{
wait(NULL);
close(fd[1]);
/* again here, you're only reading one character, there is no loop */
for (i=0;i<5;i++){
nbytes=read(fd[0],f2,sizeof(f2));
printf("%s : from parent .. waiting for next character from child\n",f2);
}}
return 0;
}
thanx for explanning the mechanism
I have another question
if I have the following code
Code:
#include<stdio.h>
#include<string.h>
int main(void){
int childpid,fd[2],nb,i,j;
char line[BUFSIZ]="I want to print this line twice";
char word[BUFSIZ] ;
pipe(fd);
childpid=fork();
if(childpid==0)
{
printf("from child:\n");
close(fd[0]);
char *token=strtok(line," ");
while(token!=NULL)
{
printf(" %s\n",token);
write(fd[1],token,(strlen(token)+1));
token=strtok(NULL," ");
}
}
else
{
wait(NULL);
printf("from parent:\n");
close(fd[1]);
for( i=0;i<7;i++){
nb=read(fd[0],word,sizeof(word));
printf("%s\n",word);
}
}
return 0;
}
I want the output to be:
from child:
I
want
to
print
this
line
twice
from parent:
I
want
to
print
this
line
twice
what I get is
from child:
I
want
to
print
this
line
twice
from parent:
I
I
I
I
I
I
I
I think I am doing as you said, but instead of the first for loop in child process I've used a while loop but I dont know why I did not get the correct results
thanx again for help