共享内存示例代码如下:

//共享内存示例代码如下:

#include <stdio.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <string.h>

typedef int sem_t;
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
sem_t CreateSem(key_t key, int value)
{
union semun sem;
sem_t semid;
sem.val = value;

semid = semget(key,value,IPC_CREAT|0666);
if (-1 == semid)
{
printf(“create semaphore error\n”);
return -1;
}

semctl(semid,0,SETVAL,sem);

return semid;
}
/*
 * struct sembuf{
 * ushort sem_num;
 * short  sem_op;
 * short  sem_flg;
 * };
 * */
void SetvalueSem(sem_t semid, int value)
{
union semun sem;
sem.val = value;

semctl(semid,0,SETVAL,sem);

return ;
}

int GetvalueSem(sem_t semid)
{
union semun sem;

return semctl(semid,0,GETVAL,sem);

return sem.val;
}

void DestroySem(sem_t semid)
{
union semun sem;
sem.val = 0;

semctl(semid,0,IPC_RMID,sem);
}

int Sem_P(sem_t semid)
{
struct sembuf sops={0,+1,IPC_NOWAIT};

return (semop(semid,&sops,1));
}

int Sem_V(sem_t semid)
{
struct sembuf sops={0,-1,IPC_NOWAIT};

return (semop(semid,&sops,1));
}

static char msg[]=”你好,共享内存\n”;

int main(void)
{
key_t key;
int semid,shmid;
char i,*shms,*shmc;
struct semid_ds buf;
int value = 0;
char buffer[80];
pid_t p;

key = ftok(“/ipc/sem/”,’a');
shmid = shmget(key,1024,IPC_CREAT|0604);

semid = CreateSem(key,1);

p = fork();
if(p > 0)
{
/* 父进程 */
/* 建立共享内存 */
shms = (char *)shmat(shmid,0,0);

memcpy(shms, msg, strlen(msg)+1);
sleep(10);
Sem_P(semid);
shmdt(shms);

DestroySem(semid);
}
else if(p == 0)
{
shmc = (char *)shmat(shmid,0,0);
Sem_V(semid);
printf(“共享内存的值为:%s\n”,shmc);

转载于:https://www.cnblogs.com/yuzaipiaofei/archive/2011/08/10/4124388.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值