#include
#include
#include
#include
#include
#include
#include
#include
#include
#if defined(_GNU_LIBRARY_) && ! defined(_SEM_SEMUN_UNDEFINED)
#else
union semun
{
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *_buf;
};
#endif
#define SHMDATASIZE 1000
#define BUFFERSIZE (SHMDATASIZE - sizeof(int))
#define SN_EMPTY 0
#define SN_FULL 1
int DeleteSemid=0;
void server(void);
void client(int shmid);
void delete(void);
void sigdelete(int sginum);
void locksem(int semid,int semnum);
void unlocksem(int semid,int semnum);
void clientwrite(int shmid,int semid,char *buffer);
int main(int argc, char *argv[])
{
if(argc<2)
server();
else
client(atoi(argv[1]));
return 0;
}
void server(void)
{
union semun sunion;
int semid,shmid;
void *shmdata;
char *buffer;
semid=semget(IPC_PRIVATE,2,SHM_R|SHM_W);
DeleteSemid=semid;
/*删除信号量*/
atexit(&delete);
signal(SIGINT,&sigdelete);
/*初始化信号量*/
sunion.val=1;
semctl(semid,SN_EMPTY,SETVAL,sunion);
sunion.val=0;
semctl(semid,SN_FULL,SETVAL,sunion);
/*分配共享内存段*/
shmid=shmget(IPC_PRIVATE,SHMDATASIZE,IPC_CREAT|SHM_R|SHM_W);
/*影射到内存空间*/
shmdata=shmat(shmid,0,0);
/*结束进程后自动删除共享内存*/
shmctl(shmid,IPC_RMID,NULL);
*(int *)shdata=semid;
buffer=shmdata+sizeof(int);
printf("server is running with id %d\n",shmid);
while(1)
{
printf("waiting untill full...");
fflush(stdout);
locksem(semid,SN_FULL);
printf("done.\n");
printf("message received:%s\n",buffer);
unlocksem(semid,SN_EMPTY);
}
}
void client(int shmid)
{
int semid;
char *buffer;
void *shmdata;
shmdata=shmat(shmid,0,0);
semid=*(int *)shmdata;
buffer=shmdata+sizeof(int);
printf("client operational:shm id is %d\n",shmid);
while(1)
{
char input[3];
printf("\n\nmenu\n1.send a message\n");
printf("2.exit\n");
fgets(input,sizeof(input),stdin);
switch(input[0])
{
case '1':clientwrite(shmid,semid,buffer);break;
case '2':exit(0);break;
}
}
}
void delete(void)
{
printf("master exiting:deleting semaphore.\n");
if(semctl(DeleteSemid,0,IPC_RMID,0)==-1)
printf("error releasing semaphore.\n");
}
void sigdelete(int signum)
{
exit(0);
}
void locksem(int semid,int semnum)
{
struct sembuf sb;
sb.sem_num=semnum;
sb.sem_op=-1;
sb.sem_flg=SEM_UNDO;
semop(semid,&sb,1);
}
void unlocksem(int semid,int semnum)
{
struct sembuf sb;
sb.sem_num=semnum;
sb.sem_op=1;
sb.sem_flg=SEM_UNDO;
semop(semid,&sb,1);
}
void clientwrite(int shmid,int semid,char *buffer)
{
printf("waiting until empty...");
fflush(stdout);
locksem(semid,SN_EMPTY);
printf("done.\n");
printf("enter message:");
fgets(buffer,BUFFERSIZE,stdin);
unlocksem(semid,SN_FULL);
}
阅读(512) | 评论(0) | 转发(0) |