【发布时间】:2019-10-23 14:12:23
【问题描述】:
这是我们的任务:编写三个通过 fifo 队列进行通信的程序。第一个程序发送偶数,第二个程序发送奇数,第三个程序接收 数字并将它们加在一起。所有流程都应在 屏幕。 我试图解决它,但我的代码无法正常工作,可能是 3 程序中的问题,请帮助。 第一个 prog 应该发送偶数,第二个奇数,第三个应该接收并将这些数字相加(总和)。第一个和第二个程序似乎执行了它们的任务,但第三个没有并冻结 我的代码:
//1 个程序
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
void prog1(int descriptor,char *fifo)
{
int a=0;
int i=0;
while (i!=10)
{
a+=2;
descriptor = open(fifo, O_WRONLY);
write(descriptor,&a, sizeof(a)+1);
puts("");
printf(" Even number : %d",a);
close(descriptor);
i++;
}
}
int main()
{
int descriptor;
char * fifo = "/tmp/myfifo_file";
mkfifo(fifo, 0666);
prog1(descriptor,fifo);
return 0;
}
//2 程序
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
void prog2(int descriptor,char *fifo)
{
int b=1;
int i=0;
while (i!=10)
{
descriptor = open(fifo, O_WRONLY);
write(descriptor, &b, sizeof(b)+1);
puts("");
printf("Odd number : %d",b);
b+=2;
close(descriptor);
i++;
}
}
int main()
{
int descriptor;
char * fifo = "/tmp/myfifo_file";
mkfifo(fifo, 0666);
prog2(descriptor,fifo);
return 0;
}
//3 程序
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
void prog3(int descriptor,char *fifo)
{
int *a;
int *b;
int i=0;
while (i!=10)
{
descriptor = open(fifo, O_RDONLY);
read(descriptor,a, sizeof(a));
close(descriptor);
descriptor = open(fifo, O_RDONLY);
read(descriptor,b, sizeof(b));
close(descriptor);
printf("Sum : %d",(*a)+(*b));
i++;
}
}
int main()
{
int descriptor;
char * fifo = "/tmp/myfifo_file";
mkfifo(fifo, 0666);
prog3(descriptor,fifo);
return 0;
}
【问题讨论】:
-
发生了什么错误?请提供有关代码实际执行的操作以及应该执行的操作的更多详细信息。
-
第一个 prog 应该发送偶数,第二个奇数,第三个应该接收并将这些数字相加(总和)。第一个和第二个程序似乎执行了它们的任务,但第三个没有并冻结。
-
@HIPHOP 请edit您的问题并在此处添加所有要求的信息或说明,而不是编写 cmets。
-
如果你想在 prog 1 和 2 中写入二进制整数值,你应该使用
write(descriptor, &b, sizeof(b));。您当前的程序会将b中存储的数字解释为地址,并从该地址读取比int的大小多一个字节。这是未定义的行为。您的程序将发送垃圾数据,甚至可能崩溃。代码中的一些错误应该会产生编译器警告。也许您必须启用警告。请修复所有警告。 -
您在 prog3 中遇到了同样的错误。现在您在 prog3 中使用未初始化的指针
a和b。不要使用sizeof(b)+1。这还将在保存变量b的内存结束后读取一个字节。与我之前评论中的代码进行比较。 顺便说一句: 不能保证 prog3 将从 prog1 中读取一个值并从 prog2 中读取一个值。它也可能发生,例如prog1 先写入所有值,然后 prog2 写入所有值。