1. IPC:inter-process communication,接下来需要了解的三种IPC:共享内存Shared memory,信号灯semophore、消息队列message queue。
有名管道可以再无亲缘关系的进程间通信,是因为用户空间有管道这种文件类型。
而这三种IPC,用户空间是没有对应的文件类型的。ftok key可以保证用户空间的二个进程对同一个IPC对象进程操作。
2. 这三中IPC对象的实现模型:
与文件IO操作的对应关系:
文件I/O | IPC |
open | Msg_get Shm_get Sem_get |
read write | msgsnd msgrecv shmat shmdt semop |
close | msgctrl shmctrl semctrl |
3. 共享内存的创建shmget:
头文件: #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
函数原型: int shmget(key_t key, int size, int shmflg)
函数参数: key:IPC_PRIVATE 或 ftok的返回值
size:共享内存区大小
shmflg:同open函数的权限位,也可以用8进制表示
返回: 成功:共享内存段标识符,ID,文件描述符
失败:-1
4. 查看IPC 共享内存对象命令:ipcs -m
5. 删除IPC 共享内存对象命令:ipcrm -m id
6. 创建出的共享内存,一块缓存,类似于用户空间的数组或malloc 函数分配的空间一样。
7. 实例,创建共享内存
#include "sys/types.h"
#include "sys/shm.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int shmid;
shmid=shmget(IPC_PRIVATE,128,0777);
if(shmid <0)
{
printf("creat share memory failure\n");
return -1;
}
printf("creat share memory sucess shmid=%d\n",shmid);
system("ipcs -m");
// system("ipcrm -m shmid");
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/011$ gcc shm.c
alex@alex-virtual-machine:/extra/process/011$ ls
a.out shm.c
alex@alex-virtual-machine:/extra/process/011$ ./a.out
creat share memory sucess shmid=2129926
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 950272 alex 600 524288 2 dest
0x00000000 1867777 alex 600 524288 2 dest
0x00000000 425986 alex 600 524288 2 dest
0x00000000 458755 alex 600 524288 2 dest
0x00000000 2064388 alex 600 524288 2 dest
0x00000000 1572869 alex 600 33554432 2 dest
0x00000000 2129926 alex 777 128 0
0x00000000 1081351 alex 600 16777216 2
0x00000000 1179656 alex 600 524288 2 dest
0x00000000 2097161 alex 600 1048576 2 dest
0x00000000 1409034 alex 600 524288 2 dest
alex@alex-virtual-machine:/extra/process/011$