1 file8 days ago
2

shmwriter.cpp

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string>
 
using namespace std;
 
class CSharedMemroy
{
 
private :
    
    int m_shmid;   
    key_t m_key;
    int *m_shared_memory;
 
 
public :
 
    void setShmId( int key );
    int getShmId();
    void setKey( key_t key );
 
    void setupSharedMemory( int size );
    void attachSharedMemory();
    void copyToSharedMemroy( int* count );
    void close();
};
 
 
void CSharedMemroy::setShmId( int id )
{
    m_shmid = id;
}
 
 
void CSharedMemroy::setKey( key_t key )
{
    m_key = key;
}
 
 
void CSharedMemroy::setupSharedMemory( int size )
{
   // Setup shared memory, 11 is the size
 
   if ( ( m_shmid = shmget(m_key, size , IPC_CREAT | 0666)) < 0 )
   {
      printf("Error getting shared memory id");
      exit( 1 );
   }
}
 
 
void CSharedMemroy::attachSharedMemory()
{
   // Attached shared memory
   if ( ( m_shared_memory = (int*) shmat( m_shmid , NULL , 0 ) ) == (int *)-1)
   {
      printf("Error attaching shared memory id");
      exit(1);
   }
}
 
 
void CSharedMemroy::copyToSharedMemroy( int* count )
{
   // copy string to shared memory
   memcpy( m_shared_memory, count , sizeof(*count) );
   //sleep( 10 );
}
 
void CSharedMemroy::close()
{
//    sleep(10);
 
   // Detach and remove shared memory
   shmdt(m_shared_memory);
   shmctl( m_shmid , IPC_RMID, NULL );
}
 
 
int main(int argc, const char **argv)
{
    CSharedMemroy m;
 
    m.setKey(7777);

    // int i;
    // i = 10;

    int temp = 10;
    int *count = &temp;

    m.setupSharedMemory(11);
    m.attachSharedMemory();

    while(1){
        // std::string s = std::to_string(i);
        m.copyToSharedMemroy(count);
        printf("Value: %d \n", temp);
        if(temp==99) temp = 10;
        temp++;
        sleep(1);
    }
    m.close();

    // m.setupSharedMemory(11);
    // m.attachSharedMemory();
 
    // m.copyToSharedMemroy("HELLO WORLD");
    // m.close();
    return 0;
}