IPC之共享存储区
用共享存储区进行进程间通信主要有以下步骤组成
1. Create shared memory
int shmget(key_t key, int size, int shmflg);
if ((shm_id = shmget (mykey, sizeof (struct sharedbuf), 0600 | IFLAGS)) < 0)
perror ("shmget");
2. Attach shared memory
char *buf = shmat (shm_id, 0, 0);
3. Read / Write shared memory
sharedbuf->size = size_;
memcpy(sharedbuf->buf, mybuf, size_);
memcpy(mybuf, sharedbuf->buf, sharedbuf->size);
3. Detach shared memory (optional)
shmdt (buf);
4. Remove shared memory
if (shmctl (shm_id, IPC_RMID, (struct shmid_ds *)0) < 0)
perror ("shmctl");
一个测试过的实例
#include <stdio.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define SHM_MODE (SHM_R | SHM_W)
#define SHM_SIZE 2048
int main()
{
int segment_id, segment_size;
char *shared_memory;
pid_t pid;
if((segment_id = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)/*获得共享内存标识符*/
perror("shmget error!\n");
if((shared_memory = shmat(segment_id, 0, 0)) == (void *)-1)/*进程和共享内存段相连接*/
perror("shmat error!\n");
printf("test1 send a message to share memory.\n");
sprintf(shared_memory, "Hello test2\n");
shmdt(shared_memory);/*脱离链接*/
pid = fork();
if(pid < 0)
perror("Creating process error!\n");
else if(pid > 0)
{
wait(NULL); /*父进程等待子进程结束*/
shmctl(segment_id, IPC_RMID, 0);/*子进程结束,父进程将共享内存删除*/
exit(0);
}
else
{
if((shared_memory = shmat(segment_id, 0, 0)) == (void*)-1)/*子进程和共享内存连接*/
perror("shmat error!\n");
printf("test2 get a message form share memory:%s",shared_memory);
shmdt(shared_memory);
}
}
相关参考:http://blog.csdn.net/Apollo_zhc/archive/2006/06/01/768694.aspx