/*
* shm.c
*
* Created on: Aug 2, 2012
* Author:Jan
*/
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#define SIZE 512
int main(int argc, char **argv)
{
int pid;
int i;
char *p;
int shmid;
shmid = shmget((key_t)9527, SIZE, IPC_CREAT); // Create shm
if (shmid < 0) {
perror("shmget");
return -1;
}
pid = fork(); // Create process
if (pid < 0)
return -1;
if (pid == 0) {
p = shmat(shmid, NULL, SHM_RND); // child
for (i = 0; i < 5; i++)
p += sprintf(p, "I'm the father ID %d\n", i);
sleep(1);
} else {
p = shmat(shmid, NULL, SHM_RND); // father
printf("%s", p);
sleep(4);
printf(p);
}
shmctl(shmid, IPC_RMID, NULL); // free mem
return 0;
}
Linux下进程之间共享内存的简单实现,步骤如下:
第一步:利用 int shmget(key_t key, size_t size, int shmflg)函数,创建一段共享内存;
这三个参数的含义:
第一个为 key号,在linux下用ipcs -m 可查看当前状态下,已启动多少进程。
第二个为你分配的内存的size。
第三个为标志位。
第二步;利用 pid_t fork(void) 创建进程;
第三步:根据fork()的返回值,判断为child、father、failed;
第四步:释放内存
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。