要求在共享内存中存入字符串“1234567”"。A进程循环打印字符串,B进程循环倒置字符串,要求结果不允许出现乱序:提示:共享内存+信号
//A进程
#include <head.h>
#include <sys/shm.h>
#include <sys/sem.h>
int main(int argc, const char *argv[])
{
//创建key
key_t key = ftok("/home/ubuntu/",'a');
if(key < 0)
{
perror("ftok");
return -1;
}
//创建内存
int shmid = shmget(key,128,IPC_CREAT|0664);
if(shmid < 0)
{
perror("shmget");
return -1;
}
//映射
void *shmaddr = shmat(shmid,NULL,0);
if(shmaddr == (void*)-1)
{
perror("shmat");
return -1;
}
char *ptr = (char *)shmaddr;
strcpy(ptr,"1234567");
system("ipcs -m");
//信号灯
int semid = semget(key,2,IPC_CREAT|0664);
if(semid < 0)
{
perror("semget");
return -1;
}
//设置信号灯
unsigned short arr[2]={0,1};
semctl(semid,0,SETALL,arr);
struct sembuf sops;
while(1)
{
//p操作
sops.sem_num = 1;
sops.sem_op = -1;
sops.sem_flg = 0;
if(semop(semid,&sops,1) < 0)
{
perror("semop");
return -1;
}
printf("%s\n",ptr);
sops.sem_num = 0;
sops.sem_op = +1;
sops.sem_flg = 0;
if(semop(semid,&sops,1) < 0)
{
return -1;
}
//v操作
}
return 0;
}
//B进程
#include <head.h>
#include <sys/shm.h>
#include <sys/sem.h>
int main(int argc, const char *argv[])
{
//创建key
key_t key = ftok("/home/ubuntu/",'a');
if(key < 0)
{
perror("ftok");
return -1;
}
//通过key值获取信号灯集
int semid = semget(key,2,IPC_CREAT|0664);
if(semid < 0)
{
perror("semget");
return -1;
}
//创建内存
int shmid = shmget(key,128,IPC_CREAT|0664);
if(shmid < 0)
{
perror("shmget");
return -1;
}
//映射
void *shmaddr = shmat(shmid,NULL,0);
if(shmaddr == (void*)-1)
{
perror("shmat");
return -1;
}
char *str = (char*)shmaddr;
char *h = NULL;
char *w = NULL;
char temp=0;
struct sembuf sops;
while(1)
{
//p操作
sops.sem_num = 0;
sops.sem_op = -1;
sops.sem_flg = 0;
if(semop(semid,&sops,1) < 0)
{
perror("semop");
return -1;
}
h = str;
w = h + strlen(str)-1;
//倒置字符
while(h < w)
{
temp = *h;
*h = *w;
*w = temp;
h++;
w--;
}
sops.sem_num = 1;
sops.sem_op = +1;
sops.sem_flg = 0;
if(semop(semid,&sops,1) < 0)
{
perror("semop");
return -1;
}
//v操作
}
return 0;
}
灯集