c - 在 C linux 中使用管道的 2 路通信

标签 c linux pipe communication fgets

我希望父进程和子进程在 C linux 中使用管道进行通信。首先,我希望 parent 传递一个字符串,然后让 child 确认它。我创建了两个文件描述符。一个用于父子,即 readpipe 和另一个用于反之亦然的 writepipe。问题是它没有将我的数据作为输入。此外,我希望打印一次诸如“输入您的数据”之类的 printf 语句,但由于在 fork 之后,有两个进程,因此它们被显示两次。还有其他选择吗??

 //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;
}

最佳答案

你打电话

    printf("\nEnter data\t"); //printed twice
    fgets(cp, 50, stdin);     //not taking data

之前您检查您是在父进程中还是在子进程中。这当然会导致两个进程都打印,并且都从标准输入中读取。所以不清楚哪个进程读取你输入的日期。

同样的问题会出现在这些行中:

 printf("\nSEND SOMETHING TO CHILD PROCESS\t");
 scanf(" %c",&ans);

我建议您重新设计您的程序,以便在 fork() 之后清楚地将在父进程中运行的代码与在子进程中运行的代码分开。

关于c - 在 C linux 中使用管道的 2 路通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22504818/

相关文章:

c - 信号 SIGTRAP 免费崩溃

c - Anti_Virus.exe 已触发断点。 C语言

c - 为什么我添加了多个节点,但我的链表只包含一个节点?

linux - 窗口是否需要图形环境才能存在?

c - 进出子进程的管道不起作用

c - fopen和open有什么关系?

linux - 修补 csv 文件会生成错误

python - 如何将执行环境传递给 SGE

C fork 和管道从文件中添加数字

c - 从管道读取字符串不一致