hw0915

#include 
int main(int argc, const char *argv[])
{
	key_t key=ftok("./",1);
	if(key<0)
	{
		perror("ftok");
		return -1;
	}
	printf("key=%#x\n",key);
	//创建共享内存
	int shmid=shmget(key,128,IPC_CREAT|0664);
	printf("shmid=%d\n",shmid);
	//映射
	void *addr=shmat(shmid,NULL,0);
	if((void*)-1==addr) perror("semget");

	//创建信号灯集
	int semid=semget(key,2,IPC_CREAT|0664);
	//初始化信号灯集
	unsigned short arr[2]={1,0};
	if(semctl(semid,0,SETALL,arr)<0)  perror("semctl");
	struct sembuf buf[2];
	buf[0].sem_num=0;
	buf[0].sem_op=-1;
	buf[0].sem_flg=0;
	buf[1].sem_num=1;
	buf[1].sem_op=1;
	buf[1].sem_flg=0;
	
	char* str=(char*)addr;
	strcpy(str,"hello world");
	while(1)
	{
		if(semop(semid,&buf[0],1)<0)
			perror("semop");
		puts(str);
		if(semop(semid,&buf[1],1)<0)
			perror("semop");
	}
	return 0;
}

2.

#include 
//逆置
void fun(char *str)
{
    int i = 0;
    int j = strlen(str) - 1;
    char temp;
    while (i < j) 
	{
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;
        j--;
    }
}
int main(int argc, const char *argv[])
{
	key_t key=ftok("./",1);
	if(key<0)
	{
		perror("ftok");
		return -1;
	}
	printf("key=%#x\n",key);
	//创建共享内存
	int shmid=shmget(key,128,IPC_CREAT|0664);
	printf("shmid=%d\n",shmid);

	//映射
	void *addr=shmat(shmid,NULL,0);
	if((void*)-1==addr) perror("semget");

	//创建信号灯集
	int semid=semget(key,128,IPC_CREAT|0664);
	//初始化信号灯集
	unsigned short arr[2]={1,0};
	if(semctl(semid,0,SETALL,arr)<0)  perror("semctl");
	struct sembuf buf[2];
	buf[0].sem_num=0;
	buf[0].sem_op=-1;
	buf[0].sem_flg=0;
	buf[1].sem_num=1;
	buf[1].sem_op=-1;
	buf[1].sem_flg=0;
	
	char* str=(char*)addr;
	while(1)
	{
		if(semop(semid,&buf[1],1)<0)
			perror("semop");
		fun(str);
		if(semop(semid,&buf[0],1)<0)
			perror("semop");
	}
	return 0;
}

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