在Linux中,进程间通信(IPC)是一种允许不同进程之间共享数据和信息的机制。管道(pipe)和消息队列(message queue)是两种常用的IPC方法。下面是如何使用它们的简要说明:
管道是一种半双工的通信方式,通常用于父子进程之间的通信。它允许一个进程将数据发送到另一个进程。管道分为无名管道和有名管道。
pipe()。示例代码:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int pipefd[2];
char buffer[1024];
// 创建无名管道
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
// 创建子进程
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
// 从管道读取数据
ssize_t len = read(pipefd[0], buffer, sizeof(buffer));
if (len > 0) {
printf("子进程收到数据: %s\n", buffer);
}
close(pipefd[0]);
} else { // 父进程
close(pipefd[0]); // 关闭读端
// 向管道写入数据
const char *msg = "Hello from parent!";
write(pipefd[1], msg, strlen(msg) + 1);
close(pipefd[1]);
}
return 0;
}
mkfifo()。示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
const char *fifo_name = "my_fifo";
mkfifo(fifo_name, 0666);
int fd = open(fifo_name, O_RDWR);
if (fd == -1) {
perror("open");
return 1;
}
// 向管道写入数据
const char *msg = "Hello from FIFO!";
write(fd, msg, strlen(msg) + 1);
// 从管道读取数据
char buffer[1024];
ssize_t len = read(fd, buffer, sizeof(buffer));
if (len > 0) {
printf("收到数据: %s\n", buffer);
}
close(fd);
unlink(fifo_name);
return 0;
}
消息队列是一种进程间通信的方法,允许进程发送和接收消息。消息队列是内核管理的数据结构,可以在不同的进程之间共享。创建和使用消息队列的函数包括msgget()、msgsnd()和msgrcv()。
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct msg_buffer {
long msg_type;
char msg_text[1024];
};
int main() {
key_t key = ftok("msg_queue_example.c", 'a');
int msgid = msgget(key, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget");
return 1;
}
// 发送消息
struct msg_buffer msg;
msg.msg_type = 1;
strcpy(msg.msg_text, "Hello from message queue!");
if (msgsnd(msgid, &msg, sizeof(msg.msg_text), 0) == -1) {
perror("msgsnd");
return 1;
}
// 接收消息
if (msgrcv(msgid, &msg, sizeof(msg.msg_text), 1, 0) == -1) {
perror("msgrcv");
return 1;
}
printf("收到消息: %s\n", msg.msg_text);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
return 1;
}
return 0;
}
这些示例代码展示了如何在Linux中使用管道和消息队列进行进程间通信。在实际应用中,您可能需要根据具体需求进行调整。