Wednesday, January 19, 2011

a pgm involving shared memory plus file handling!

//parent stores names of 2 files and child finds which one has greater size
#include
#include
#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,fd1,fd2;
int size=20,size1=0,size2=0;
struct sembuf semaphore;
key_t shm_key=1234,sem_key=4567;char * shm,*iterator;
int shm_id,sem_id;char temp[10];char ch;
shm_id=shmget(shm_key,size,IPC_CREAT|0666);
shm=shmat(shm_id,NULL,0);
sem_id=semget(sem_key,1,IPC_CREAT|0666);
initsem(sem_id,MUTEX,1);
childpid=fork();
if (childpid==0)
{ //child
sleep(5);
down(sem_id,MUTEX,&semaphore);
printf("\n child process reads file names\n ");
for(i=0;i<2;i++)
{ printf("\n%s\n",shm+10*i);
}

strcpy(temp,shm);
fd1=open(temp,O_RDONLY);
if(fd1==-1)
printf("\n unable to open file %s",temp);
else
{ size1=0;
while(read(fd1,&ch,sizeof(ch)))
{ size1++;
}
}
strcpy(temp,shm+10);
fd2=open(temp,O_RDONLY);
if(fd2==-1)
printf("\n unable to open file %s",temp);
else
{ size2=0;
while(read(fd2,&ch,sizeof(ch)))
{ size2++;
}
}
if(size1>size2)
printf("%s has more memory:%d",shm,size1);
else
printf("%s has more memory:%d",shm+10,size2);

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<2)
{ printf("\n k=%d,n=%d",k,2);
printf("\nenter string no. %d ",k+1);
scanf("%s",temp);
strcpy(iterator,temp);

k++;iterator+=10;
}
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"
    #include"fcntl.h"
    #include"sys/stat.h"

    ReplyDelete