c - why return in if and else not working -
i have simple doubt. trying 2 processes comm using named pipes. it's working fine press n ans, it's not executing return of main. printing "received child : " in parent process.
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include<string.h> #include<ctype.h> #include<wait.h> #define np1 "/tmp/np1" #define np2 "/tmp/np2" #define max_buf_size 255 #include <sys/types.h> int main() { int rdfd, wrfd, ret_val, count, numread; char buf[max_buf_size]; char ans; char cp[50]; pid_t pid; ret_val = mkfifo(np1,0666); if ((ret_val == -1) && (errno != eexist)) { perror("error creating named pipe"); exit (1); } ret_val = mkfifo(np2, 0666); if ((ret_val == -1) && (errno != eexist)) { perror("error creating named pipe"); exit (1); } printf("\nsend parent process\t"); scanf("%[^\n]%*c",&ans); pid=fork(); if (pid==-1) { printf("\nerror in pid"); exit(1); } while (ans=='y' || ans=='y') { if (pid!=0) { //parent process /* open first named pipe reading */ rdfd = open(np1, o_rdonly); numread = read(rdfd, buf, max_buf_size); buf[numread] = '\0'; printf("received child : %s\n", buf); /* convert string upper case */ count = 0; while (count < numread) { buf[count] = toupper(buf[count]); count++; } wrfd = open(np2, o_wronly); /* write converted string second pipe */ write(wrfd, buf, strlen(buf)); } else { //child process printf("\nenter data sent parent\t"); fgets(cp, 50, stdin); wrfd = open(np1, o_wronly); /* write pipe */ write(wrfd, cp, strlen(cp)+1); /* open second named pipe reading */ rdfd = open(np2, o_rdonly); /* read pipe */ numread = read(rdfd, buf, max_buf_size); buf[numread] = '\0'; printf("received parent : %s\n", buf); printf("\nsend parent process\t"); fflush(stdin); scanf(" %[^\n]%*c",&ans); } } return 0; }
the problem code when u give n input child, parent still alive in order kill parent use return read in parent see if child has exited or not , if child exit, exit parent too. can done editing code with
if( (numread = read(rdfd, buf, max_buf_size)) == 0) return 0;
actually once give n input in child, child exits , old value of ans y compared in parent process , doesn't exit....
check n reply... thanks...
Comments
Post a Comment