linux核间通信的代码,使用共享内存的方式
时间: 2024-05-27 07:13:45 浏览: 14
以下是使用共享内存实现Linux核间通信的示例代码:
// 主进程
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
typedef struct {
int num;
char str[1024];
} data;
int main() {
int shmid;
data *shared_memory;
int running = 1;
void *shmaddr;
// 创建共享内存
shmid = shmget((key_t)1234, sizeof(data), 0666 | IPC_CREAT);
if (shmid == -1) {
perror("shmget failed");
exit(EXIT_FAILURE);
}
// 将共享内存附加到进程中
shmaddr = shmat(shmid, (void *)0, 0);
if (shmaddr == (void *)-1) {
perror("shmat failed");
exit(EXIT_FAILURE);
}
shared_memory = (data *)shmaddr;
// 主进程写入数据
shared_memory->num = 123;
strcpy(shared_memory->str, "hello world");
// 等待子进程读取完数据
while (running) {
if (shared_memory->num == -1) {
running = 0;
}
}
// 分离共享内存
if (shmdt(shmaddr) == -1) {
perror("shmdt failed");
exit(EXIT_FAILURE);
}
// 删除共享内存
if (shmctl(shmid, IPC_RMID, 0) == -1) {
perror("shmctl(IPC_RMID) failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
// 子进程
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
typedef struct {
int num;
char str[1024];
} data;
int main() {
int shmid;
data *shared_memory;
void *shmaddr;
// 连接到共享内存
shmid = shmget((key_t)1234, sizeof(data), 0666 | IPC_CREAT);
if (shmid == -1) {
perror("shmget failed");
exit(EXIT_FAILURE);
}
shmaddr = shmat(shmid, (void *)0, 0);
if (shmaddr == (void *)-1) {
perror("shmat failed");
exit(EXIT_FAILURE);
}
shared_memory = (data *)shmaddr;
// 子进程读取数据
printf("num: %d\n", shared_memory->num);
printf("str: %s\n", shared_memory->str);
// 修改数据
shared_memory->num = 456;
strcpy(shared_memory->str, "hello linux");
// 将数据读取完毕的信号发送给主进程
shared_memory->num = -1;
// 分离共享内存
if (shmdt(shmaddr) == -1) {
perror("shmdt failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}