【发布时间】:2021-04-14 21:30:54
【问题描述】:
我用管道制作了这个程序来与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 程序未从其他子进程接收消息。当我用Write() 打印buf 变量时,它只显示一个字母。它应该显示整个消息,这就是它处于 while 循环中的原因。我怎样才能做到这一点?我还没有找到任何关于 fork 进程和 FIfO 的信息,希望你能帮助我。
【问题讨论】:
-
请注意,您没有提出问题,也没有描述具体问题。
-
对此我很抱歉。我现在已经添加了问题
-
sizeof(texto + 1)不确定您要在那里做什么。为什么要将 1 添加到 array 中?也许您打算将大小加 1。但即使这样也是错误的。你不能写超过缓冲区中的内容。它应该是strlen(texto)+1。 -
while (nbytes = read(fd2, buf, 8) == 8)必须是while ((nbytes = read(fd2, buf, 8)) == 8)。因为==的优先级高于=。您将 1 或 0(布尔结果)分配给nbytes。 -
非常感谢您的工作!您可以复制 cmets 进行回复,如果您愿意,我可以将其标记为正确