在C中的subprocess和父进程之间的通信linux:父进程不阻塞

我想让父进程和subprocess在C使用pipe道进行通信。 首先,我想要父母传递一个string,然后孩子承认它。 我创build了两个文件描述符。 一个为父母对孩子即读音pipe和另一个反向笔pipe。 问题是它不把我的数据作为input。 另外,我希望printf语句(如“input您的数据”)被打印一次,但自fork之后,有两个进程,所以它们被显示两次。 任何替代scheme?

//readpipe[0] = child read //readpipe[1]= parent write //writepipe[0]=parent read //writepipe[1]=child write #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main(void) { pid_t pid; int r; /* Hope this is big enough. */ char buf[1024]; char cp[50]; char ans; int readpipe[2]; int writepipe[2]; int a; int b; a=pipe(readpipe); b=pipe(writepipe); if (a == -1) { perror("pipe"); exit(EXIT_FAILURE); } if (b == -1) { perror("pipe"); exit(EXIT_FAILURE); } printf("\nSEND SOMETHING TO CHILD PROCESS\t"); scanf(" %c",&ans); pid=fork(); if(pid==-1) { printf("pid:main"); exit(1); } while(ans=='y' || ans=='Y') { printf("\nEnter data\t"); //printed twice fgets(cp, 50, stdin); //not taking data printf("\n%s",cp); if(pid==0) { //CHILD PROCESS close(readpipe[1]); close(writepipe[0]); read(readpipe[0],buf,sizeof(buf)); printf("\nSENT\n %s",buf); write(writepipe[1],cp,strlen(cp)+1); } else { //PARENT PROCESS close(readpipe[0]); close(writepipe[1]); write(readpipe[1],cp,strlen(cp)+1); read(writepipe[0],buf,sizeof(buf)); printf("\nRECEIVED\n %s",buf); } printf("\nSEND SOMETHING TO CHILD PROCESS\t"); scanf(" %c",&ans); } close(readpipe[1]); close(writepipe[0]); close(readpipe[0]); close(writepipe[1]); return 0; } 

谢谢 :)

Solutions Collecting From Web of "在C中的subprocess和父进程之间的通信linux:父进程不阻塞"

你的代码有几个问题:

1。

 close(writepipe[1]); 

您不应该关闭稍后需要的文件描述符。

2。

 read(readpipe[0],ch,sizeof(ch)); 

chNULL ,这意味着你没有分配任何空间来指向它。

3。

 ch1="YES"; write(writepipe[1],ch1,sizeof(ch1)); 

您应该使用strlen(ch)+1而不是sizeof(ch)来查找需要写入的字节数。

4。

你的父进程的代码有类似的问题。


这里是一个基于这个问题代码的固定版本:

 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main(void) { pid_t pid; int r; /* Hope this is big enough. */ char buf[1024]; char *cp; int readpipe[2]; int writepipe[2]; int a; int b; a=pipe(readpipe); b=pipe(writepipe); // check a and b pid=fork(); // check pid if(pid==0) { //CHILD PROCESS close(readpipe[1]); close(writepipe[0]); read(readpipe[0],buf,sizeof(buf)); printf("\nREAD = %s",buf); close(readpipe[0]); cp="YES\n"; write(writepipe[1],cp,strlen(cp)+1); close(writepipe[1]); } else { //PARENT PROCESS close(readpipe[0]); close(writepipe[1]); cp="HI!! YOU THERE"; write(readpipe[1],cp,strlen(cp)+1); close(readpipe[1]); read(writepipe[0],buf,sizeof(buf)); printf("\nACK RECEIVED %s",buf); close(writepipe[0]); } return 0; }