IO周二作业

在共享内存中存入字符串“1234567”。A进程循环打印字符串,B进程循环倒置字符串,要求结果不允许出现乱序。
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, const char *argv[])
{
	key_t key = ftok("./",10);
	if(key < 0 )
	{
		perror("ftok");
		return -1;
	}
	printf("%#x \n",key);
	int shmid = shmget(key,128,IPC_CREAT|0664);
	if(shmid<0)
	{
		perror("shmget");
		return -1;
	}
	printf("shmid = %d\n",shmid);
	void* shmaddr = shmat(shmid,NULL,0);
	if((void*)-1 == shmaddr)
	{
		perror("shmaddr");
		return -1;
	}
	printf("shmaddr = %p \n",shmaddr);
	char *str = (char*)shmaddr;
	char *start =str;
	char *end = str+strlen(str)-1;
	char temp = 0;
	struct sembuf sop;


	while(1)
	{
		temp = *start;
		*start = temp;
		*end = temp;

		start++;
		temp--;
	}
	sop.sem_num = 1;
	sop.sem_op = +1;
	sop.sem_flg = 0;
	if(semop(shmid,&sop,1)<0)
	{
		perror("semop");
		return -1;
	}
		
	return 0;
}
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, const char *argv[])
{
	key_t key = ftok("./",10);
	if(key<0)
	{
		perror("ftok");
		return -1;
	}
	printf("%#x\n",key);
	//创建信号灯集
	int semid = semget(key,2,IPC_CREAT|0664);
	if(semid < 0)
	{
		perror("semget");
		return -1;
	}
	//设置信号灯的值
	unsigned short arr[2]={0,1};
	if(semctl(semid,0,SETALL,arr)<0)
	{
		perror("semctl");
		return -1;
	}
	//创建共享内存
	int shmid = shmget(key,128,IPC_CREAT|0664);
	if(shmget<0)
	{
		perror("shmge");
		return -1;
	}
	printf("shmid = %d \n",shmid);

	//映射到用户空间
	void *shmaddr = shmat(shmid,NULL,0);
	if((void*)-1 == shmaddr)
	{
		perror("shmaddr");
		return -1;
	}
	printf("shmaddr = %p\n",shmaddr);
	char * str = (char*)shmaddr;
	strcpy(str,"123456");
	struct sembuf sop;
	while(1)
	{
		sop.sem_num = 1;  //控制1号灯
		sop.sem_op = -1;  //p操作
		sop.sem_flg = 0;  //阻塞方式
		if(semop(semid,&sop,1)<0)
		{
			perror("semop");
			return -1;
		}
		printf("%s\n",str);
		sop.sem_num = 0;  //控制0号灯
		sop.sem_op = +1;  //V操作
		sop.sem_flg = 0;  //阻塞方式
		if(semop(semid,&sop,1)<0)
		{
			perror("semop");
			return -1;
		}
	}
	return 0;
}

你可能感兴趣的:(算法)