time - C- program using fork won't exit after user inputs 'exit' -
we tasked create two-way communication simulation in 1 c code. it's first time dabbling kind of code have created simple code:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include<wait.h> int main(void) { pid_t pid; char buf[1024]; char cp[50]; char ex[100]="exit"; int readpipe[2]; int writepipe[2]; long int a; int b; a=pipe(readpipe); b=pipe(writepipe); int test=1; int length; if (a == -1) { perror("pipe"); exit(exit_failure); } if (b == -1) { perror("pipe"); exit(exit_failure); } fflush(stdin); pid=fork(); if(pid==-1) { printf("pid:main"); exit(1); } while(test==1) { if(pid==0) { close(readpipe[1]); close(writepipe[0]); if(read(readpipe[0],buf,sizeof(buf)) < 0) { exit(1); } printf("\nsend user 1:"); fflush(stdin); fgets(cp, 50, stdin); length = strlen(cp); if(cp[length-1] == '\n') { --length; cp[length] = '\0'; } if(strcmp(cp,ex)==0) { test=0; break; } if(write(writepipe[1],cp,strlen(cp)+1) < 0) { exit(1); } } else { close(readpipe[0]); close(writepipe[1]); printf("\nsend user 2:"); fflush(stdin); fgets(cp, 50, stdin); length = strlen(cp); if(cp[length-1] == '\n') { --length; cp[length] = '\0'; } if(strcmp(cp,ex)==0) { test=0; break; } if(write(readpipe[1],cp,strlen(cp)+1) < 0) { exit(1); } if(read(writepipe[0],buf,sizeof(buf)) < 0) { exit(1); } } } close(readpipe[1]); close(writepipe[0]); close(readpipe[0]); close(writepipe[1]); return 0; }
the program terminates when user 1 or user 2 inputs exit. however....
the error whenever press exit, print "send user x" first proceeds exit. how can fix this? help? thanks.
when type exit
sending process, breaks out of loop, closes end of pipes, , exits.
when other process tries read pipe, eof, indicated read()
returning 0
. code never checks this, exits when read()
or write()
returns negative value indicate error (eof not error). goes top of loop , asks input send other process. when tries write closed pipe epipe
error or sigpipe
signal, , exit.
change reading code to:
int n = read(readpipe[0],buf,sizeof(buf)); if (n == 0) { break; } else if (n < 1) { exit(1); }
Comments
Post a Comment