英译中:
这是消费者代码。
我正在使用以下命令编译生产者和消费者:gcc -o my_program my_program.c
要重现问题,您需要打开9个终端来运行每个生产者和1个终端来运行消费者。 执行消费者:./consumer 同时在所有终端中执行生产者,将相关联的ID通过命令行传递给每个执行文件。例如:./producer 0,./producer 1。
在生产者发送消息若干次(平均10次)之后,任意一个生产者将突然停止执行,显示问题。
以下图像描述了执行情况: 准备执行的终端 以下图像描述了生产者ID 3的错误 生产者3的错误 提前致谢。
我正在用C语言实现一个管道,其中多个生产者程序(在我的例子中有9个)将数据写入一个单一的消费者程序。
问题是,当调用write()函数时,一些生产者(有时一个或两个)突然退出程序。
代码很简单,以下是生产者代码:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#define MSG_SIZE_BYTES 4
void send(unsigned int * msg){
int fd, msg_size;
int r;
char buffer [5];
char myfifo[50] = "/tmp/myfifo";
fd = open(myfifo, O_WRONLY);
if(fd == -1){
perror("error open SEND to fifo");
}
r = write(fd, msg, MSG_SIZE_BYTES);
if(r == -1){
perror("error writing to fifo");
}
close(fd);
printf("Message send\n");
}
int main(int argc, char *argv[]){
int cluster_id = atoi(argv[1]);
unsigned int msg[1];
msg[0] = cluster_id;
while(1){
printf("Press a key to continue...\n");
getchar();
send(msg);
}
}
这是消费者代码。
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#define MSG_SIZE_BYTES 4
int receive(unsigned int * received_msg){
int fd, msg_size;
int ret_code;
char buffer [5];
char myfifo[50] = "/tmp/myfifo";
fd = open(myfifo, O_RDONLY);
if(fd == -1)
perror("error open RECV to fifo");
ret_code = read(fd, received_msg, MSG_SIZE_BYTES);
close(fd);
if (ret_code == -1){
printf("\nERROR\n");
return 0;
}
return 1;
}
void main(){
mkfifo("/tmp/myfifo", 0666);
unsigned int msg[1];
while(1){
receive(msg);
printf("receive msg from id %d\n", msg[0]);
}
}
我正在使用以下命令编译生产者和消费者:gcc -o my_program my_program.c
要重现问题,您需要打开9个终端来运行每个生产者和1个终端来运行消费者。 执行消费者:./consumer 同时在所有终端中执行生产者,将相关联的ID通过命令行传递给每个执行文件。例如:./producer 0,./producer 1。
在生产者发送消息若干次(平均10次)之后,任意一个生产者将突然停止执行,显示问题。
以下图像描述了执行情况: 准备执行的终端 以下图像描述了生产者ID 3的错误 生产者3的错误 提前致谢。
msg
缓冲区。 - pbn