shmget
得到一个共享内存标识符或创建一个共享内存对象并返回共享内存标识符
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);
RETURN VALUE
On success, a valid shared memory identifier is returned.
On error, -1 is returned, and errno is set to indicate
the error.
ftok
ftok 可以生成一个可生成 key_t 类型 的key;
#include <sys/types.h>
#include <sys/ipc.h>
key_t ftok(const char *pathname, int proj_id);
RETURN VALUE
On success, the generated key_t value is returned. On
failure -1 is returned, with errno indicating the error
as for the stat(2) system call.
shmat
连接共享内存标识符为shmid的共享内存,连接成功后把共享内存区对象映射到调用进程的地址空间,随后可像本地空间一样访问
#include <sys/types.h>
#include <sys/shm.h>
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr);
RETURN VALUE
On success, shmat() returns the address of the attached
shared memory segment; on error, (void *) -1 is returned,
and errno is set to indicate the cause of the error.
int shmdt(const void *shmaddr);
On success, shmdt() returns 0; on error -1 is returned, and errno is set to indicate the cause of the error.
#include "head.h"
int main() {
pid_t pid;
int shmid;
char *share_memory = NULL;
key_t key = ftok("./2_sh.c", 329); // 获得 key;
if ((shmid = shmget(key, 4096, IPC_CREAT | IPC_EXCL | 0666)) < 0) { //创建共享内存;
perror("shmget");
exit(1);
}
if ((share_memory = shmat(shmid, NULL, 0)) < 0) { // 连接共享内存‘;
perror("shmat");
exit(1);
}
if ((pid = fork()) < 0) { // 创建子进程;
perror("fork()");
exit(1);
}
if (pid) {
while(1) {
scanf("%s", share_memory); // 从父进程读入内容到共享内存;
getchar(); // 吃掉回车;
}
}
else {
while(1) {
sleep(2);
printf("<child> : %s\n", share_memory); // 子进程中打印共享内存中的内容;
memset(share_memory, 0, 4096);
}
}
return 0;
}