hi all

I am trying to be much familier with pipes

I tried to write a c program that generates the following output


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

my code is

#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;

}

can any one tell me what's wronge with this code and how to correct it? :sad:

Recommended Answers

All 2 Replies

You can tell yourself. You understand how every individual part works, right? So simulate the code by hand, and you'll see where it's going wrong.

I know what the problem is and I've solved it

thanx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.