#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg); key: 函数ftok返回值,或者IPC_PRIVATE ,当使用IPC_PRIVATE时,最好两个进程空间是共享的,比如父子进程,否则当前进程产生的共享内存标识(返回值),在另一个进程里面不易得到; #include <sys/types.h>
#include <sys/shm.h>
void *shmat(int shmid, const void *shmaddr, int shmflg);
int shmdt(const void *shmaddr); shmid:是函数shmget函数返回的共享内存标识符。 #include <sys/ipc.h>
#include <sys/shm.h>
int shmctl(int shmid, int cmd, struct shmid_ds *buf);int sln_shm_get(char *shm_file, void **mem, int mem_len)
{
int shmid;
key_t key;
if (NULL == fopen(shm_file, "w+")) {
printf("fopen: %s\n", strerror(errno));
return -1;
}
key = ftok(shm_file, 0);
if (key < 0) {
printf("ftok: %s\n", strerror(errno));
return -1;
}
shmid = shmget(key, mem_len, IPC_CREAT);
if (shmid < 0) {
printf("shmget: %s\n", strerror(errno));
return -1;
}
*mem = (void *)shmat(shmid, NULL, 0);
if ((void *)-1 == *mem) {
printf("shmat: %s\n", strerror(errno));
return -1;
}
return shmid;
}
int main(int argc, const char *argv[])
{
char *shm_file = NULL;
char *shm_buf = NULL;
int shmid;
shmid = sln_shm_get(SHM_IPC_FILENAME, (void **)&shm_buf, SHM_IPC_MAX_LEN);
if (shmid < 0) {
return -1;
}
snprintf(shm_buf, SHM_IPC_MAX_LEN, "Hello system V shaare memory IPC! this is write by server.");
sleep(15);
printf("System V server delete share memory segment!\n");
//shmdt(shm_buf);
shmctl(shmid, IPC_RMID, NULL); //server在15秒之后destroy该片共享内存,此时客户进程将获取不到共享内存的内容
return 0;
}
client process:
int sln_shm_get(char *shm_file, void **mem, int mem_len)
{
int shmid;
key_t key;
key = ftok(shm_file, 0);
if (key < 0) {
printf("ftok: %s\n", strerror(errno));
return -1;
}
shmid = shmget(key, mem_len, IPC_CREAT);
if (shmid < 0) {
printf("shmget: %s\n", strerror(errno));
return -1;
}
*mem = (void *)shmat(shmid, NULL, 0);
if ((void *)-1 == *mem) {
printf("shmat: %s\n", strerror(errno));
return -1;
}
return shmid;
}
int main(int argc, const char *argv[])
{
char *shm_buf = NULL;
int i;
if (sln_shm_get(SHM_IPC_FILENAME, (void **)&shm_buf, SHM_IPC_MAX_LEN) < 0) {
return -1;
}
printf("ipc client get: %s\n", shm_buf);
return 0;
}
# ipcs ------ Message Queues -------- key msqid owner perms used-bytes messages ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x0010a797 131072 root 0 4096 1 ------ Semaphore Arrays -------- key semid owner perms nsems
# ./client ipc client get: Hello system V shaare memory IPC! this is write by server. #
# ipcs ------ Message Queues -------- key msqid owner perms used-bytes messages ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status ------ Semaphore Arrays -------- key semid owner perms nsems 此时共享内存已经不在了,但文件依然存在。 # ./client ipc client get: #
# cat /proc/sys/kernel/shmmax 33554432 #
原文:http://blog.csdn.net/shallnet/article/details/41171099