#include <mystdio.h>
int main(int argc, const char *argv[])
{
//创建key值
key_t key = ftok("/home/ubuntu",2);
if(key<0)
{
perror("ftok");
return -1;
}
printf("key=%#x\n",key);
//创建信号灯集
int semid = semget(key,2,IPC_CREAT|0664);
if(semid < 0)
{
perror("semget");
return -1;
}
//设置信号灯值
unsigned short brr[2] = {0,1};
if(semctl(semid,0,SETALL,brr)<0)
{
perror("semctl");
return -1;
}
//通过key值寻找共享内存
int shmid = shmget(key,128,IPC_CREAT|0664);
if(shmid<0)
{
perror("shmget");
return -1;
}
printf("shmid=%#x\n",shmid);
//将共享内存映射到用户空间
void* adr = shmat(shmid,NULL,0);
if((void*)-1 == adr)
{
perror("shmat");
return -1;
}
printf("adr = %p\n",adr);
char* ptr = (char*)adr;
strcpy(ptr,"1234567");
struct sembuf sop;
while(1)
{
sop.sem_num = 1;
sop.sem_op = -1;
sop.sem_flg = 0;
if(semop(semid,&sop,1) < 0)
{
perror("semop");
return -1;
}
printf("%s\n",ptr);
sop.sem_num = 0;
sop.sem_op = +1;
sop.sem_flg = 0;
if(semop(semid,&sop,1) <0)
{
perror("semop");
return -1;
}
}
return 0;
}
#include <mystdio.h>
int main(int argc, const char *argv[])
{
//找到key值
key_t key = ftok("/home/ubuntu",2);
if(key <0)
{
perror("ftok");
return -1;
}
printf("key=%#x\n",key);
//创建信号灯集
int semid = semget(key,2,IPC_CREAT|0664);
if(semid < 0)
{
perror("semget");
return -1;
}
//通过key值寻找共享内存
int shmid = shmget(key,128,IPC_CREAT|0664);
if(shmid<0)
{
perror("shmget");
return -1;
}
printf("shmid=%#x\n",shmid);
//将共享内存映射到用户空间
void* adr = shmat(shmid,NULL,0);
if((void*)-1 == adr)
{
perror("shmat");
return -1;
}
printf("adr = %p\n",adr);
char* ptr = (char*)adr;
char* start = NULL;
char* end = NULL;
char temp=0;
struct sembuf sop;
while(1)
{
sop.sem_num = 0;
sop.sem_op = -1;
sop.sem_flg = 0;
if(semop(semid,&sop,1)<0)
{
perror("semop");
return -1;
}
start = ptr;
end = start + strlen(ptr)-1;
while(start < end)
{
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
sop.sem_num = 1;
sop.sem_op = +1;
sop.sem_flg = 0;
if(semop(semid,&sop,1) < 0)
{
perror("semop");
return -1;
}
}
return 0;
}