C fork two children and pipe between parent and children

I'm trying to fork two children. Parent reads a line send to pipe. Child one reads it and write it to another pipe and finally child2 reads it. However, the output is always parent getting line. Thanks! #define MAX 80 void child(); void parent(); void childtwo(); char * getli(); void printline(char *buffer, int count); char * convertCase(char *str); int pipe1[2]; int pipe2[2]; int main(int argc, char **argv) { pipe(pipe1); pipe(pipe2); if(fork()){ if(fork()){ printf("1st\n"); parent(); exit(0); } else{ printf("3rd\n"); childtwo(); exit(0); } } else{ printf("2nd\n"); child(); exit(0); } } void child(){ char *buf; int count = 0; close(pipe1[1]); close(pipe2[0]); while(1){ buf = (char *) malloc(sizeof(char)*MAX); read(pipe1[0], buf, MAX); if (strcmp(buf,"quit")== 0){ printf("Child is leaving\n"); free(buf); break; } else{ printf("Child: "); printline(buf,strlen(buf)); write(pipe2[1],buf, strlen(buf)+1); free(buf); } close(pipe2[1]); close(pipe1[0]); exit(0); } } void childtwo() { char *buf; int count = 0; close(pipe2[1]); buf = (char *) malloc(sizeof(char)*MAX); while(1){ buf = (char *) malloc(sizeof(char)*MAX); read(pipe2[0], buf, MAX); if (strcmp(buf,"quit")== 0){ printf("Childtwo is leaving\n"); free(buf); break; } else{ printf("Childtwo:"); printline(buf,strlen(buf)); free(buf); } } close(pipe2[0]); exit(0); } void parent(){ char * buffer; int count = 0, done=0; close(pipe1[0]); while (done != 1){ printf("parent getting line: "); buffer = getli(); write(pipe1[1],buffer, strlen(buffer)+1); if (strcmp(buffer,"quit")== 0){ puts("parent goes away"); free(buffer); break; } free(buffer); } close(pipe1[1]); exit(0); }
You have a memory leak in your child processes, you allocate buf both before the loops, and inside the loops.

以上就是C fork two children and pipe between parent and children的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏