Saket Soni


back to readerwriter
back to home


#include
#include
#include
#include
#include
#include
#include
#include

int main()
{
	int semid, pid;
	int iCount = 0;
	struct sembuf sop;
	int semKey = 32;
	int semVal = 0;
	int semNo  = 0;

	printf ( "Creating a semaphore set (with 4 semaphores) with semaphore set key : %d\n", semKey );
	semid = semget ( semKey, 4, IPC_CREAT|0666);
	if ( semid == -1 )	{
		perror ( "semaphore set creation failed " );
		exit(1);
	}
	printf ( "Semaphore set created with sem id : %d\nNow initializing semaphore values ...\n", semid );

	semVal = 1;
	for ( semNo = 0 ; semNo < 4 ; semNo++ )
	{
		printf ( "  semaphore %d : %d  ", semNo, semVal);
		if ( semNo == 3 )
			semVal = 0;
		int stat = semctl ( semid, semNo, SETVAL, semVal );
		if ( stat == -1 )	{
			perror ( "could not set the semaphore value " );
			printf ( "\ndeleting the semaphore set id : %d\n", semid );
			int stat = semctl ( semid, 0, IPC_RMID, 0 );
			if ( stat == -1 )	{
				perror ( "semaphore deletion failed " );
				exit ( 1 );
			}
			printf ( "semaphore set with id : %d deleted\nexiting ...\n", semid );			
			exit ( 1 );
		}
		printf ( "  set !!\n" );
	}

	int shmid;
	key_t shKey = 0x1000;
	int shSize = sizeof(int)*2;
	printf ( "Now creating a shared memory of size %d, with key : %d", shSize, shKey );
	shmid = shmget ( shKey, shSize, IPC_CREAT|0666 );
	if ( shmid == -1 )	{
		perror ( "cannot allocated shared memory " );
		printf ( "\ndeleting the semaphore set id : %d\n", semid );
		int stat = semctl ( semid, 0, IPC_RMID, 0 );
		if ( stat == -1 )	{
			perror ( "semaphore deletion failed " );
			exit ( 1 );
		}
		printf ( "semaphore set with id : %d deleted\nexiting ...\n", semid );			
		exit(1);
	}
	printf ( "Shared memory created with id : %d\nNow initializing shared memory ...\n", shmid );
	
	int * ptr = (int *) shmat ( shmid, 0, 0 );
	int & ReaderCount = *ptr;
	int & DataChangeCount = *(ptr+1);
	ReaderCount    = 0;
	DataChangeCount = 0;
	printf ( "Shared memory initialized with ReadCount = %d and DataChangecount = %d\n",
				ReaderCount, DataChangeCount);

	int k = 0;
	while ( 1 )
	{
		printf ( "(%4d) :: ", k++ );
		int WriterCount = semctl ( semid, 3, GETVAL, 0 );
		printf ( "Reader Count : %6d | Writer Count : %6d | DataChangeCount : %6d\n" ,
					ReaderCount, WriterCount, DataChangeCount );
		sleep(1);
	}
}



back to readerwriter
back to home

Locations of visitors to this page 1