1 file9 days ago
3

#include <stdio.h>

Trao doi du lieu giua c va python thong qua shared memory

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

void setChar(int *num, int val){
   *num = val;
}

int main(int argc, const char **argv)
{
   int shmid;
   // give your shared memory an id, anything will do
   key_t key = 123456;
   int *shared_memory;

// Setup shared memory, 11 is the size
   if ((shmid = shmget(key, 11, IPC_CREAT | 0666)) < 0)
   {
      printf("Error getting shared memory id");
      exit(1);
   }
   // Attached shared memory
   if ((shared_memory = shmat(shmid, (int *)0, 0)) == (int *) -1)
   {
      printf("Error attaching shared memory id");
      exit(1);
   }
  
   int *count;
   setChar(&count, 0);
   int temp = 0;
   while(1){
      temp += 1;
      setChar(&count, temp);
       // copy "hello world" to shared memory
      memcpy(shared_memory, count , 8);
      // sleep so there is enough time to run the reader!
      sleep(0.00005);
   }

   // Detach and remove shared memory
   shmdt(shmid);
   shmctl(shmid, IPC_RMID, NULL);
   printf("Finish share mem testing \n");
}