Click to See Complete Forum and Search --> : programming on linux


Astrid
03-17-2002, 03:27 PM
sorry to bother u guys. but i need help on an assignment i have. we're programming on a linux platform and we have to use a pipe to communicate between a child and parent process. my program isnt working. something is wrong with the parent writing to the pipe. the error msg i get is "Parent Write: bad file descriptor". here is my code if anyone is willing to help plz :p

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char buf[100];
int fd[2], n;

// will create a pipe to communicate
if ( -1 == pipe( fd ) ){
perror("pipe");
return -1;
}

// will create child and close the appropiate ends of the pipe
switch ( fork() ) {
case -1: // an error has occured
perror("fork");
break;
case 0: // child proccess
if ( close(fd[0]) == -1 ) { // wont write
perror("close stdin");
break;
}
printf("child running\n");
fprintf( stdout, "------c1\n");
while(1) {
fprintf( stdout, "------c2\n");
n = read( fd[1], buf, sizeof(buf) );
fprintf( stdout, "------c3\n");
if ( n == -1 ){
printf("Child Read");
_exit(1);
}
else if ( n == 0 ){
printf("Child Done\n");
_exit(0);
}
if ( -1 == write( 1, buf, n )){
perror("Child: Write");
_exit(1);
}
} // end of while
break;
default: // parent proccess
if ( close(fd[1]) == -1 ) { //wont read
perror("close stdout");
}

printf("parent running\n");
fprintf( stdout, "------p1\n");
while(1) {
fprintf( stdout, "------p2\n");
n = read( STDIN_FILENO, buf, sizeof(buf));
fprintf( stdout, "------p3\n");
if ( -1 == n ){
perror("Parent read");
_exit(1);
}
else if ( 0 == n ){
printf("Parent Done\n");
close( fd[0] );
break;
}
if ( -1 == write( fd[0], buf, n )){
perror("Parent Write");
close( fd[0] );
break;
}
} // end of while
break;
} // end of switch

return 0;
}

Astrid
03-17-2002, 04:48 PM
n/m i got it :D

recluse.
03-17-2002, 06:12 PM
Just a tip for next time when you post code put it between the "Code" tags so the indentation is kept intact. You should see the button below the area where you type your message. Glad you figured out your problem!