linux:生产者消费者模型
warning:
这篇文章距离上次修改已过188天,其中的内容可能已经有所变动。
在Linux环境下实现生产者-消费者模型,可以使用管道和 Posix 消息队列(mqueue)。以下是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#define BUFFER_SIZE 128
#define PATHNAME "/tmp/prodcon"
// 消息结构体
typedef struct {
long msg_type;
char msg_text[BUFFER_SIZE];
} Msg;
// 生产者函数
void* producer(void* arg) {
int fd = *(int*)arg;
char buf[BUFFER_SIZE];
while (1) {
// 生产数据
snprintf(buf, BUFFER_SIZE, "Message from producer: %ld", time(NULL));
// 写入管道
write(fd, buf, strlen(buf) + 1);
sleep(1);
}
return NULL;
}
// 消费者函数
void* consumer(void* arg) {
int fd = *(int*)arg;
char buf[BUFFER_SIZE];
while (1) {
// 读取管道数据
read(fd, buf, BUFFER_SIZE);
printf("Consumer received: %s\n", buf);
sleep(2);
}
return NULL;
}
int main() {
int pipefd[2];
pid_t pid;
int ret;
// 创建管道
ret = pipe(pipefd);
if (ret == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建消费者进程
if ((pid = fork()) == 0) {
// 子进程:消费者
close(pipefd[1]); // 关闭写端
consumer((void*)&pipefd[0]);
exit(EXIT_SUCCESS);
}
// 创建生产者进程
close(pipefd[0]); // 关闭读端
producer((void*)&pipefd[1]);
// 等待消费者进程结束
wait(NULL);
close(pipefd[1]);
return 0;
}
这段代码首先创建一个管道,然后创建一个生产者进程和一个消费者进程。生产者进程往管道写数据,消费者进程从管道读数据。这个模型演示了进程之间通过管道进行通信的基本方法。
评论已关闭