hi there!here's the problem in a nutshell:
there are 2 files.the program creates 2 processes:
the parent process outputs text lines from the 1st file and for each one of these lines the child process outputs relative info from the 2nd file.
e.g.
<1st line from file1>
<relative info from file2>
<relative info from file2>
...
<2nd line from file1>
<relative info from file2>
...
the problem is that after printing everything it keeps running. to be more specific, the parent process remains in a wait state and the child process gets stuck in a pipe_w state.
I'm clearly missing something but can't seem to be able to find it, so any help would be much appreciated!
here's the code:
#include <stdio.h>
#include <string.h>
void client(int readfd, int writefd);
void server(int readfd, int writefd);
int main(){
int childpid, pipe[2], pipe[2], status;
if((pipe(pipe1)< 0)||pipe(pipe2)< 0)){
printf("Pipes were not created.\n";
exit(1);
}
childpid = fork();
if(childpid == -1){
printf("Server wasn't created.\n);
exit(1);
}
if(childpid > 0){ //parent
close(pipe2[1]);
close(pipe1[0]);
client(pipe2[0], pipe1[1]);
wait(&status);
close(pipe2[0]);
close(pipe1[1]);
exit(0);
}
else{ //child
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
close(pipe1[0]);
close(pipe2[1]);
exit(0);
}
return 0;
}//end of main
void client(int readfd, int writefd){
FILE *fp;
fp = fopen("file1", "r");
char buff[1024];
char comm[320];
char am[80];
while(fgets(buff, sizeof buff, fp) != NULL){
printf("%s \n", buff);
//...(am is initialised here)
writefd(writefd, am, strlen(am));
while(read(readfd, comm, sizeof comm) <= 0){}
}
fclose(fp);
}
void server(int readfd, int writefd){
char buff[1024];
char am[80];
while(read(readfd, am, sizeof am) > 0){
FILE *fp;
fp = fopen("file2", "r");
while(fgets(buff, sizeof buff, fp) != NULL){
//...
}
write(writefd, "done", 4);
fclose(fp);
}
}