One more question about forks/pipes
Thanks again to all who helped me out yesterday. I tried to finish up this program (takes 2 chars from user [using forking/pipes] and outputs them). This is what I have so far and it isn't working:
Code:
#include <stdio.h>
int main( int argc, char * argv[] ){
int i, j, buff = 0;
char p[2];
char string[256];
if( pipe(p)==-1 ){
printf("pipe failed");
exit(-1);
}
printf("Enter two chars to compare: \n");
for(i; i<2; i++) {
switch( fork() ){
case 0:
buff = getchar();
printf("PID of child %d is %d\n", i+1, getpid() );
write( p[1], &buff, sizeof(int) );
return 0;
break;
case -1:
printf("A forking error has occurred\n");
exit(-1);
break;
default:
break;
}
}
printf( "PID of parent is %d\n", getpid() );
while( i-- ){
read( p[0], &buff, sizeof(int) );
printf("this came out: %c\n", buff);
}
}
when I compile and run I get the following:
Code:
bash-2.03$ gcc -oq2 q2.c
bash-2.03$ q2
Enter two chars to compare:
PID of parent is 9624
t
this came out:
g
PID of child 2 is 9626
PID of child 1 is 9625
c
this came out:
bash-2.03$
Can anybody tell me whats wrong?