linux进程通信之共享内存高级议题
2017-05-10 20:52
295 查看
共享内存如果不删除就让进程死亡,则这片内存是没有释放的。
如果进程中有没有调用shmdt进行分离,则内存的连接计数仍然保持,即使使用ipcrm -m 共享内存id 命令进行删除后连接计数扔保持。
在用fork创建子进程之前创建并连接内存,子进程会继承,在之后创建和连接也是可以的。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define BUF_SIZE 1024
#define MYKEY 25
int main()
{
int shmid;
char *shmptr;
if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1)
{
printf("shmget error \n");
exit(1);
}
shmptr =shmat(shmid,0,0);
if( shmptr == (void *)-1)
{
perror("shmat error!\n");
exit(1);
}
if(fork() == 0)
{
printf("%d\n",shmptr);
while(1)
{
printf("input:");
scanf("%s",shmptr);
}
}
else
{
printf("%d\n",shmptr);
while(1)
{
printf("string :%s\n",shmptr);
sleep(3);
}
}
exit(0);
}
如果进程中有没有调用shmdt进行分离,则内存的连接计数仍然保持,即使使用ipcrm -m 共享内存id 命令进行删除后连接计数扔保持。
在用fork创建子进程之前创建并连接内存,子进程会继承,在之后创建和连接也是可以的。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define BUF_SIZE 1024
#define MYKEY 25
int main()
{
int shmid;
char *shmptr;
if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1)
{
printf("shmget error \n");
exit(1);
}
shmptr =shmat(shmid,0,0);
if( shmptr == (void *)-1)
{
perror("shmat error!\n");
exit(1);
}
if(fork() == 0)
{
printf("%d\n",shmptr);
while(1)
{
printf("input:");
scanf("%s",shmptr);
}
}
else
{
printf("%d\n",shmptr);
while(1)
{
printf("string :%s\n",shmptr);
sleep(3);
}
}
exit(0);
}
相关文章推荐
- linux基础编程:进程通信之System V IPC:消息队列,信号量,共享内存
- Linux 进程通信--共享内存
- 【linux高级环境编程学习笔记三】共享内存通信
- Linux进程通信-共享内存
- linux下进程间共享内存通信的问题
- Linux 进程通信--共享内存
- Linux进程通信之POSIX共享内存
- linux下通过共享内存在进程之间实现通信(system V)
- linux进程间共享内存通信详解
- Linux进程通信之POSIX共享内存
- linux进程通信:共享内存(转)
- Linux进程通信总结(三) --共享内存
- Linux下进程通信之共享内存
- Linux进程通信 共享内存
- 进程通信之内存地址映射与共享,同时如何在Linux0.11下实现共享内存
- Linux 进程通信--共享内存。
- linux进程通信--共享内存
- linux 进程通信之共享内存
- UNIX/LINUX编程学习之进程通信--共享内存
- linux 进程间的通信(五) 共享内存-1