标签:rdo 基本操作 oid 创建者 led 命名 完成 mode quit
共享内存使用的函数介绍
int shmget(key_t key, size_t size, int shmflg);
void *shmat(int shm_id, const void *shm_addr, int shmflg);
int shmdt(const void *shm_addr);
int shmctl(int shm_id, int cmd, struct shmid_ds *buf);
shmid_ds结构至少包含以下成员:
struct shmid_ds {
uid_t shm_perm.uid;
uid_t shm_perm.gid;
mode_t shm_perm.mode;
}
#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> typedef struct stu { char name[32]; int age; } STU; int main(int argc, char *argv[]) { int shmid; shmid = shmget((key_t)1234,sizeof(STU),IPC_CREAT | 0666); if (shmid == -1) { printf("shmget failed\n"); exit(1); } STU *p; p = shmat(shmid,NULL,0); if (p == (void*)-1) { printf("shmat failed\n"); exit(1); } strcpy(p->name, "zhangsan"); p->age = 20; while(1) { if(memcmp(p, "quit",4) == 0) { break; } } shmdt(p); shmctl(shmid,IPC_RMID,NULL); return 0; }
shmread.c
#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> typedef struct stu { char name[32]; int age; } STU; int main(int argc, char *argv[]) { int shmid; shmid = shmget((key_t)1234,0,0); if (shmid == -1) { printf("shmget failed\n"); exit(1); } STU *p; p = shmat(shmid,NULL,0); if (p == (void*)-1) { printf("shmat failed\n"); exit(1); } printf("name = %s, age = %d\n",p->name,p->age); memcpy(p,"quit",4); shmdt(p); return 0; }
Makefile
.PHONY: clean all CC=gcc CFLAGS=-Wall -g BIN=shmwrite shmread all:$(BIN) %.o:%.c $(cc) $(CFLAGS) -c $< -o $@ clean: rm -f *.o $(bin)
参考:http://blog.chinaunix.net/uid-26000296-id-3421346.html
标签:rdo 基本操作 oid 创建者 led 命名 完成 mode quit
原文地址:http://www.cnblogs.com/Malphite/p/7669078.html