2019-11-06 11:05:11 +01:00
//
// Created by Cigerxwin Chaker on 05.11.19.
//
# include <iostream>
2019-11-06 11:54:26 +01:00
# include <sys/types.h>
2019-11-06 11:05:11 +01:00
# include <sys/ipc.h>
# include <sys/shm.h>
# include <stdio.h>
# include <stdlib.h>
# include <sys/stat.h>
# include <sys/sem.h>
# include <unistd.h>
2019-11-06 11:54:26 +01:00
# include <cstring>
# include "SharedMemoryAccess.h" /* header is important for the shmID. name could be different. maybe not needed cause: (shmget(memory_access_key, NULL, 0)) */
2019-11-06 11:05:11 +01:00
int initSemaphore ( void ) {
/* Testen, ob das Semaphor bereits existiert */
2019-11-06 11:54:26 +01:00
semId = semget ( SEM_KEY , 0 , IPC_PRIVATE ) ;
2019-11-06 11:05:11 +01:00
if ( semId < 0 ) {
/* ... existiert noch nicht, also anlegen */
/* Alle Zugriffsrechte der Dateikreierungsmaske */
/* erlauben */
umask ( 0 ) ;
2019-11-06 11:54:26 +01:00
semId = semget ( SEM_KEY , 1 , IPC_CREAT | IPC_EXCL | PERM ) ;
2019-11-06 11:05:11 +01:00
if ( semId < 0 ) {
return - 1 ;
}
/* Semaphor mit 1 initialisieren */
if ( semctl ( semId , 0 , SETVAL , ( int ) 1 ) = = - 1 )
return - 1 ;
}
return 1 ;
}
int semaphoreOperation ( int op ) {
semaphore . sem_op = op ;
semaphore . sem_flg = SEM_UNDO ;
if ( semop ( semId , & semaphore , 1 ) = = - 1 ) {
perror ( " semop " ) ;
exit ( EXIT_FAILURE ) ;
}
return 1 ;
}
void writeToShm ( char * text , int size ) {
2019-11-06 11:38:46 +01:00
int shmId = shmget ( memoryAccessKey , NULL , 0 ) ; // dont init just get the ID if already existing.
2019-11-06 11:05:11 +01:00
if ( shmId < 0 ) {
exit ( EXIT_FAILURE ) ;
/* we could return -1, not sure if it will be useful to continue after there is no shm allocated for any reason*/
} else {
char * shm_pointer = ( char * ) shmat ( shmId , NULL , 0 ) ;
2019-11-06 11:54:26 +01:00
semaphoreOperation ( LOCK ) ;
2019-11-06 11:05:11 +01:00
memcpy ( shm_pointer , text , size ) ;
2019-11-06 11:54:26 +01:00
semaphoreOperation ( UNLOCK ) ;
2019-11-06 11:05:11 +01:00
}
}
char * getShmPointer ( ) {
int shmId = shmget ( memoryAccessKey , NULL , 0 ) ;
if ( shmId < 0 ) {
exit ( EXIT_FAILURE ) ;
/* we could return -1, not sure if it will be useful to continue after there is no shm allocated for any reason*/
} else {
return ( char * ) shmat ( shmId , NULL , 0 ) ;
}
}