#include
#include
#include
#include
#include
#include
int main(int argc,char *argv[])
{
pid_t pid;
if((pid=fork())>0)
{
int shid;
void *sharem=NULL;
int semid;
int value;
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_flg=SEM_UNDO;
int flag=1;
if((semid=semget((key_t)12345,1,0666|IPC_CREAT))==-1)
{
perror("semget\n");
exit(0);
}
if(semctl(semid,0,SETVAL,0)==-1)
{
perror("semctl init\n");
if(semctl(semid,0,IPC_RMID,0)!=0)
{
perror("semctl del\n");
exit(0);
}
exit(0);
}
if((shid=shmget((key_t)255,(size_t)2048,0600|IPC_CREAT))==-1)
{
perror("shmget\n");
exit(0);
}
if((sharem=shmat(shid,NULL,0))==NULL)
{
perror("shmat\n");
exit(0);
}
while(flag)
{
if((value=semctl(semid,0,GETVAL))==0)
{
printf("write data opreate\n");
scanf("%s",(char *)sharem);
sem_b.sem_op =1;
if(semop(semid,&sem_b,1)==-1)
{
perror("semop\n");
exit(1);
}
}
if(strcmp(sharem,"end")==0)
flag--;
}
shmdt(sharem);
if(shmctl(shid,IPC_RMID,0)==-1)
{
perror("shmctl remove shm\n");
exit(0);
}
}
else if(pid==0)
{
int shid;
void *sharem=NULL;
int semid;
int value;
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_flg=SEM_UNDO;
int flag=1;
if((semid=semget((key_t)12345,1,0666|IPC_CREAT))==-1)
{
perror("semget\n");
exit(0);
}
if(semctl(semid,0,SETVAL,0)==-1)
{
perror("semctl init\n");
if(semctl(semid,0,IPC_RMID,0)!=0)
{
perror("semctl del\n");
exit(0);
}
exit(0);
}
if((shid=shmget((key_t)255,(size_t)2048,0600|IPC_CREAT))==-1)
{
perror("shmget\n");
exit(0);
}
if((sharem=shmat(shid,NULL,0))==NULL)
{
perror("shmat\n");
exit(0);
}
while(flag)
{
if((value =semctl(semid,0,GETVAL))==1)
{
printf("read data opreate\n");
printf("%s\n",(char *)sharem);
sem_b.sem_op=-1;
if(semop(semid,&sem_b,1)==-1)
{
perror("semop\n");
exit(1);
}
}
if(strcmp(sharem,"end")==0)
flag--;
}
shmdt(sharem);
}
else
{
perror("error\n");
return 0;
}
return 0;
}
阅读(1501) | 评论(0) | 转发(0) |