/* * Project 3 - Shared memory and semaphores. * Dr. Silaghi's Operating System Concepts. * main.c - Main entry point for the client application. * By: Michael Rywalt - 2569 */ #include #include #include #include "main.h" /************** * InitScreen * ************** * * Function: InitScreen * * Purpose: Print welcome message to user when application begins. * * Parameters: None. * * Returns: Nothing. */ void InitScreen() { printf("Welcome to the cilent application.\n"); printf("r - read current counter value.\nw - write a new value to counter.\nq - quit.\n"); } /******************* * IsDaemonRunning * ******************* * * Function: IsDaemonRunning * * Purpose: To check if the daemon is running. It must be running * for the client to run. * * Parameters: None. * * Returns: TRUE if running, FALSE if not. */ int IsDaemonRunning() { int iDaemonsLockFile; /* Set up a lockfile so no other instances of this daemon run at once. */ iDaemonsLockFile = open(LOCKFILE, O_RDWR | O_CREAT, 0640); /* Validate lockfile. */ if(iDaemonsLockFile < 0) { perror(" [IsDaemonRunning] "); exit(EXIT_ERROR); } if(lockf(iDaemonsLockFile, F_TLOCK, 0) < 0) { return 1; } return 0; } /******** * main * ******** * * Function: main * * Purpose: Main entry point. * * Parameters: None for this program. * * Returns: EXIT_OK on success, * EXIT_ERROR on error. */ int main() { /* The integer that comes from the shared memory segment. */ int *pInteger = NULL; int iValue = 0; char cUserEntry = 0; char szValue[256]; /* Check if daemon is running first... */ if(!IsDaemonRunning()) { printf("Daemon doesn't appear to be running. Try starting it first.\n"); exit(EXIT_ERROR); } /* Use existing semaphores from daemon. */ InitSemaphore(); /* Use shared memory that daemon set up. */ pInteger = InitSharedMemory(); /* Prompt user with basic instructions before starting. */ InitScreen(); /* Main loop. */ do { printf("> "); /* The daemon must be running and must exit after we do. */ if(!IsDaemonRunning()) { printf("Daemon has disappeared. Aborting.\n"); exit(EXIT_ERROR); } switch(cUserEntry) { case 'w': fflush(stdin); printf("Enter new value [or -1 to cancel action]: "); scanf("%s", szValue); iValue = atoi(szValue); if(iValue != -1) { if(SEMAPHORE(&WaitMutex) == 0) { *pInteger = iValue; } SEMAPHORE(&SignalMutex); } else { printf("Cancelled.\n"); } case 'r': if(SEMAPHORE(&WaitMutex) == 0) { printf("Counter value: %i\n", *pInteger); } SEMAPHORE(&SignalMutex); break; default: break; } }while((cUserEntry = getchar()) != 'q'); printf("Quitting...\n"); /* Exit. */ return 0; }