首页 > 解决方案 > 使用 FIFO 通信两个子 fork 进程

问题描述

我用管道制作了这个程序来与两个进程通信PIPES。现在我要做的是相同的,但使用FIFO.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>
#include <string.h>
int main()
{
    int e, p[20], hijo1, hijo2, nbytes, readbytes;
    char texto[200], readbuffer[100];

    printf("Write the message to send to the other process\n");
    fgets(texto, 100, stdin);

    pipe(p);
    if ((hijo1 = fork()) == -1)
    {
        printf("ERROR FORK\n");
        exit(EXIT_FAILURE);
    }
    if (hijo1 == 0)
    {
        printf("Im %d  and Im child 1\n", getpid());
        close(p[0]); 

        write(p[1], texto, strlen(texto + 1));
        close(p[1]);
        exit(0);
    }
    if ((hijo2 = fork()) == -1)
    {
        printf("ERROR FORK\n");
        exit(EXIT_FAILURE);
    }

    if (hijo2 == 0)
    {
        printf("Im %d And Im child 2 \n", getpid());
        close(p[1]);

        write(1, "message received: ", 24);
        while ((nbytes = read(p[0], readbuffer, 8)) == 8)
        {
            write(1, readbuffer, nbytes);
        }
        write(1, readbuffer, nbytes);
        printf("\n");
        close(p[0]);
        exit(0);
    }
    printf("Im %d and Im the father\n", getpid());
    waitpid(hijo1, &e, 0);
    waitpid(hijo2, &e, 0);
    exit(EXIT_SUCCESS);
    
}

这就是我试图做的,但使用 FIFO

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>
#include <string.h>
int main()
{
   char texto[200], buf[200];
   int fd, fd2, hijo1, hijo2, nbytes;
   printf("Ingrese el mensaje para enviar al FIFO\n");
   fgets(texto, 100, stdin);

   printf("soy %d y soy el padre \n", getpid());
   mkfifo("/tmp/mi_fifo", 0666);

   if ((hijo1 = fork()) == -1)
   {
      printf("ERROR FORK\n");
      exit(EXIT_FAILURE);
   }
   if (hijo1 == 0)
   {
      printf("soy %d y soy el hijo 1 \n", getpid());

      fd = open("/tmp/mi_fifo", O_WRONLY);
      write(fd, texto, sizeof(texto + 1));
      close(fd);
      exit(0);
   }
   if ((hijo2 = fork()) == -1)
   {
      printf("ERROR FORK\n");
      exit(EXIT_FAILURE);
   }
   if (hijo2 == 0)
   {
      printf("soy %d y soy el hijo 2 \n", getpid());
      fd2 = open("/tmp/mi_fifo", O_RDONLY);

      write(1, "el mensaje recibido es: \n", 24);
      while (nbytes = read(fd2, buf, 8) == 8)
      {
         write(1, buf, nbytes);
      }
      write(1, buf, nbytes);

      close(fd2);
      exit(0);
   }
   return 0;
}

此 Fifo 程序未从其他子进程接收消息。当我用它打印buf变量时,Write()它只显示一个字母。它应该显示整个消息,这就是它处于 while 循环中的原因。我怎样才能做到这一点?我还没有找到任何关于 fork 进程和 FIfO 的信息,希望你能帮助我。

标签: clinux

解决方案


至少有两个问题:

  1. sizeof(texto + 1)需要strlen(texto)+1确保缓冲区中字符串的大小正确。

  2. while(nbytes = read(fd2, buf, 8) == 8)需要是 while ((nbytes = read(fd2, buf, 8)) == 8)。因为==具有比 更高的优先级=。您将 1 或 0(布尔结果)分配给nbytes.


推荐阅读