{
int i;
sem_t * sem;
- time_t t;
- char * res;
void * shm_ptr;
+ time_t t;
/*
* Input section: decode command line parameters
* Use getopt function
usage();
}
Signal(SIGINT, HandSigInt);
- // Get shared memory segment
- shm_ptr = CreateShm(shmname, MSGMAXSIZE, 0666, 0);
- if ( shm_ptr == NULL) {
+ // get a shared memory segment
+ if ((shm_ptr = CreateShm(shmname, MSGMAXSIZE, 0666, 0)) == NULL) {
perror("Cannot find shared memory");
exit(1);
}
- // set initial string
- strncpy((char *) shm_ptr, argv[optind], MSGMAXSIZE);
- // open the semaphore or create it locked
- if ( (sem = sem_open(semname, O_CREAT, 0666, 0)) == SEM_FAILED ) {
+ // get a locked semaphore
+ if ((sem = sem_open(semname, O_CREAT|O_EXCL, 0666, 0)) == SEM_FAILED) {
perror("Cannot open semaphore");
exit(1);
}
- // check if first time creation, and unlock
- if ( sem_getvalue(sem, &i) != 0) {
- perror("cannot get initial semaphore value");
+ // set initial string
+ strncpy((char *) shm_ptr, argv[optind], MSGMAXSIZE);
+ // do initial release
+ if (sem_post(sem) != 0) {
+ perror("cannot do semaphore initial release");
exit(1);
- } else {
- if (i == 0) {
- if ( sem_post(sem) != 0) {
- perror("cannot do semaphore initial release");
- exit(1);
- }
- }
- }
+ }
+ // main loop
while(1) {
- // acquire semaphore
- if ( sem_wait(sem) != 0) {
+ if (sem_getvalue(sem, &i) !=0) { // get sem values
+ perror("cannot get semaphore value");
+ exit(1);
+ }
+ printf("sem=%i, ", i); // print sem values
+ t = time(NULL); // get time
+ printf("%s", ctime(&t)); // print time
+ if (sem_wait(sem) != 0) { // acquire semaphore
perror("cannot use semaphore");
exit(1);
}
- t = time(NULL);
- printf("%s", ctime(&t));
- sem_getvalue(sem, &i);
- printf("sem=%i, ", i);
- printf("message: %s\n", (char *) shm_ptr );
- if ( sem_post(sem) != 0) {
+ printf("message: %s\n", (char *) shm_ptr ); // print message
+ if (sem_post(sem) != 0) { // release semaphore
perror("cannot release semaphore");
exit(1);
}
void HandSigInt(int sig)
{
- RemoveShm(shmname);
- sem_unlink(semname);
+ if (RemoveShm(shmname) != 0) perror("Cannot remove shared memory");
+ if (sem_unlink(semname)!= 0) perror("Cannot remove semaphore") ;
exit(0);
}