与另外两个进程的通信进程

标签 c linux systems-programming

我逐行阅读了以下文件 (file.txt):

    1
   -5
   6
  -8
  -33
  21

父进程向一个进程发送负数,向第二个进程发送正数:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

void Fils1(int *tube1)
{
  int n;
  int cpt = 0;
  close (tube1[1]);

  while (read (tube1[0], &n, 1) >0)
  {
    cpt+=n;
  }

  printf("Son 1, count : %i \n", cpt);
  exit (1) ;
}

void Fils2(int *tube2)
{
  int n;
  int cpt = 0;
  close (tube2[1]);

  while (read (tube2[0], &n, 1) >0)
  {
    cpt+=n;
  }

  printf("Son 2, count : %i \n", cpt);
  exit (1) ;
}


int main(int argc, char *argv[])
{
 FILE* file;
 int n;

 file = fopen (argv[1], "r");

 if (file == NULL){
      printf("Error open file %s\n", argv[1]);
      exit(1);
  }

 int tube1[2];
 int tube2[2];


 if (pipe(tube1) != 0)
 {
   fprintf(stderr, "Error tube 1\n");
   return EXIT_FAILURE;
 }


 if (pipe(tube2) != 0)
 {
   fprintf(stderr, "Error tube 2\n");
   return EXIT_FAILURE;
 }

 int pid1 = fork();

 if(pid1 == 0)
 {
    printf("Creation of the first son ! \n");
    Fils1 (tube1);
 }
 else
 {
    int pid2 = fork();
    if(pid2 == 0)
    {
      printf("Creation of the second son ! \n");
      Fils2 (tube2);
    }
    else
    {
       printf("I'm the father! \n");

       close (tube1[0]);
       close (tube2[0]);

       while (!feof(file))
       {
         fscanf (file,"%d",&n);
         if (n>0)
         {
             write (tube1[1], &n, 1);
         }
         else
         {
           write (tube2[1], &n, 1);
         }
       }
      fclose (file); 

      if(wait(NULL) == -1)
      {
        printf("Error wait()\n");
        exit(1);
      }
    }
 }

 return EXIT_SUCCESS;
}

每个儿子都在数数,并显示在屏幕上。

当我执行时,我只有那个:

I'm the father!
Creation of the first son!
Creation of the second son!

当我也期待

   Son1, count : 28
   Son2, count : 46

最佳答案

问题是您没有按应有的方式关闭管道。

  • Child1 应该关闭 tube2(两端)
  • Child2 应该关闭 tube1(两端);
  • parent 应该关闭写结束(在while之后)

关于与另外两个进程的通信进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337263/

相关文章:

c - 使用 C 进行客户端服务器编程速度慢

c - 在 C 中使用指针访问多维数组的最简单方法

linux - 不支持 Xattrs

c - 套接字的所有操作都需要检查 EINTR 吗?

.net - 在 Windows 中以编程方式重启 USB 设备

c - 我如何获得用户的操作系统?

c - "Invalid argument"关于在 C 中使用 fcntl

C - 计算从 X 年到 Y 年的所有日期

php - 即使具有(似乎)正确的文件权限,上传目标文件夹似乎也不可写

有人可以解释这个输出吗?