Synchronized shared memory server and client in C

Client writes  a text in shared memory.
Then server reads that and convert to upper case and write back to shared memory.
Client reads toggled text from shared memory.
//Server
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0660 | IPC_CREAT);

semctl(semId,0,SETVAL,0);
semctl(semId,1,SETVAL,0);
shmId = shmget(MY_KEY, SHM_SIZE, 0660 | IPC_CREAT);

pShm=shmat(shmId,NULL,0);

while(1)
{
smop.sem_num = 0;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);

strcpy(pShm+256,pShm);
toggleCase(pShm+256, strlen(pShm+256));

smop.sem_num = 1;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

}
return 0;
}

void toggleCase(char* buff, int cnt)
{
printf("\ntoggle\n");
int ii;
for(ii=0;ii<cnt;ii++)
{
if((buff[ii]>='A')&&(buff[ii]<='Z'))
buff[ii]+=0x20;
else if((buff[ii]>='a')&&(buff[ii]<='z'))
buff[ii]-=0x20;
}
}

//Client
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

#define MSG_LEN 256
#define RESP_MSG_START 256

//void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0);

//semctl(semId,0,SETVAL,0);
//semctl(semId,1,SETVAL,0);

shmId = shmget(MY_KEY, SHM_SIZE,0);

pShm=shmat(shmId,NULL,0);

fgets(pShm,MSG_LEN,stdin);

smop.sem_num = 0;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

smop.sem_num = 1;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);
puts(pShm+RESP_MSG_START);
return 0;
}

//void toggleCase(char* buff, int cnt)
//{
//printf("\ntoggle\n");
//}

//terminal 1: ./server
//terminal 2: ./client
india
check
//terminal 1: 
//terminal 2:
INDIA  

No comments:

Post a Comment