Wednesday, January 19, 2011

IPC using shared memory-11

//parent reads n strings in shared memory and child finds palindromes
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MUTEX 0
///////////////////
void up(int sem_id,int sem_num,struct sembuf* semaphore)
{ semaphore->sem_num=sem_num;
semaphore->sem_op=1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
////////////////////
void down(int sem_id,int sem_num,struct sembuf* semaphore)
{ semaphore->sem_num=sem_num;
semaphore->sem_op=-1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
//////////////////////////////
void initsem(int sem_id,int sem_num,int val)
{ union semum
{ int val;
struct semid_ds* buf;
unsigned short* array;
}argument;
argument.val=val;
semctl(sem_id,sem_num,SETVAL,argument);
}
////////////////////////////////
void main()
{ pid_t childpid;
int i=0,k=0,n;
printf("\n enter the no of strings(<=10)");
scanf("%d",&n);
int size=n*10;
struct sembuf semaphore;
key_t shm_key=1234,sem_key=4567;char * shm,*iterator;
int shm_id,sem_id,j,no,flag=1;char temp[5];
shm_id=shmget(shm_key,size,IPC_CREAT|0666);
shm=shmat(shm_id,NULL,0);
//shm=shmo;
sem_id=semget(sem_key,1,IPC_CREAT|0666);
initsem(sem_id,MUTEX,1);
childpid=fork();
if (childpid==0)
{ //child
sleep(5);//shm=shmo;
down(sem_id,MUTEX,&semaphore);
printf("\n child process prints sorted strings\n ");
for(i=0;i { printf("\n%s\n",shm+5*i);
}
printf("\n palindromes are");
for(i=0;i { flag=1;
strcpy(temp,shm+5*i);
no=strlen(temp);
for(j=0;j { if (temp[j]!=temp[no-1-j])
{ flag=0;

}
}
if(flag)
printf("\n %s\n",temp);
}
up(sem_id,MUTEX,&semaphore);
}
else
{//parent
printf("\n parent process takes and sends no.s");

down(sem_id,MUTEX,&semaphore);
k=0;iterator=shm;
while(k { printf("\n k=%d,n=%d",k,n);
printf("\nenter string no. %d ",k+1);
scanf("%s",temp);
strcpy(iterator,temp);

k++;iterator+=5;
}
up(sem_id,MUTEX,&semaphore);
waitpid(childpid,NULL,0);
}
}//end of main

1 comment:

  1. #include"stdio.h"
    #include"sys/types.h"
    #include"unistd.h"
    #include"string.h"
    #include"stdlib.h"
    #include"sys/shm.h"
    #include"sys/ipc.h"
    #include"sys/wait.h"
    #include"sys/sem.h"

    ReplyDelete