linux C学习笔记02--共享内存(进程同步)

system V下3中进程同步:共享内存(shared memory),信号量(semaphore)和消息队列(message queue)

调试了下午,终于调通啦! 运行./c.out 输出共享内存中的内容,运行 ./c.out arg1 对共享内存区进行修改,shell下输入ipcs -m 可以查看共享内存情况 ,-s 是信号量,-q 是消息队列

下面先贴上main的代码:

#include <signal.h>        //head file of define signal
#include <pthread.h>
#include <static_lib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h> extern int create_shm(char **shmptr);
int main(int argc,char* argv[])
{
//IPC share memory
char *shmptr;
if(create_shm(&shmptr) == -)
{
printf("create_shm error \n");
return -;
}
if(argc > )
{
//do the second thing for share memory
while()
{
printf("input str to share memory:");
gets(shmptr);
}
}
else
{
memcpy(shmptr,"hello",);
while()
{
sleep();
printf("share memory is %s \n",shmptr);
   }
}
return ;
}

下面是共享内存创建的代码:

/*************************************************************************
> File Name: share_memory.c
> Author: hailin.ma
> Mail: mhl2018@126.com
> Created Time: Wed 27 May 2015 11:19:26 PM CST
************************************************************************/ #include<stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <errno.h> #define SHARE_MEM_KEY 26 int create_shm(char **shmptr)
{
int shmid; //if((shmid = shmget(IPC_PRIVATE,200,IPC_CREAT|IPC_EXCL|0666)) == -1)
if((shmid = shmget(SHARE_MEM_KEY,,IPC_CREAT|IPC_EXCL|)) == -)
{
perror("shmget");
if(errno == EEXIST)
{
shmid = shmget(SHARE_MEM_KEY,,);
if(shmid == -)
{
perror("shmget2");
return -;
}
else
{
if((*shmptr = shmat(shmid,,)) == (void*)-)
{
perror("shmat2");
return -;
}
else
{
return shmid;
}
}
}
else
{
return -;
}
} if((*shmptr = shmat(shmid,,)) == (void*)-)
{
perror("shmat");
return -;
} return shmid;
}

运行效果:

linux C学习笔记02--共享内存(进程同步)

05.29日增加了共享内存释放和删除:

int main(int argc,char* argv[])
{ //IPC share memory
char *shmptr;
int shmid;
if((shmid =create_shm(&shmptr)) == -)
{
printf("create_shm error \n");
return -;
}
if(argc > )
{
//do the second thing for share memory
while()
{
printf("input str to share memory:");
gets(shmptr);
if(shmptr[] == 'q') //quit
{
shmdt(shmptr); //disconnect to the share memory but will not dellect the memery
break;
} }
}
else
{
while()
{
sleep();
printf("share memory is: %s \n",shmptr);
if(shmptr[] == 'q')
{
shmdt(shmptr);
shmctl(shmid,IPC_RMID,NULL); //delete the share memery
break;
}
}
}
}
 
上一篇:Jmeter进行数据库压测


下一篇:VMware NAT端口映射外网访问虚拟机linux