I wanted to share the data on the shared library between the processes that are attaching it, so I made a lot of trial and error, but I was a little addicted to it, so I will write it as an article.
Unlike Windows DLLs, UNIX-like shared libraries are placed in the memory space of each process even if variables are placed in the global space, so interprocess communication cannot be performed simply by using the shared library. Shared memory is the easiest way to share the data used by a shared library. So here is the sample code.
lib_shared_memory.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/shm.h>
static void *sharedmemory; //Pointer to shared memory
static int seg_id; //Shared memory ID
static int* pnumattachproc;//Number of processes attached to shared memory(Placed on shared memory)
__attribute__ ((constructor))
void attach_shmem(void)
{
int isfirstproc = 0;
key_t key = 10;
size_t size = 1000;
//Create shared memory
seg_id = shmget(key, size, IPC_CREAT | IPC_EXCL | 0660);
//Failed to create,And if shared memory with the same key exists
if ((seg_id == -1) && (errno == EEXIST)){
//Get the id of that shared memory
seg_id = shmget(key, size, 0);
}else if(seg_id > 0){
//If the shared memory is created successfully, set a flag to perform initialization processing.
isfirstproc = 1;
}
if (seg_id == -1)
exit(1);
//Attach shared memory
sharedmemory = shmat(seg_id, NULL, 0);
if(isfirstproc){
pnumattachproc = (int*)sharedmemory;
//Initialize the number of attached processes
*pnumattachproc = 0;
}
(*pnumattachproc)++; //Increment the number of attached processes
}
__attribute__ ((destructor))
void detach_shmem(void)
{
(*pnumattachproc)--; //Decrement the number of attached processes
if(*pnumattachproc == 0){
//If the number of attached processes reaches 0,
//Give the shared memory the release attribute
shmctl(segid, IPC_RMID, NULL);
}
//Shared memory detach
(void) shmdt(sharedmemory);
}
int get_attachproc_num(void){
return *pnumattachproc;
}
The build uses the options for shared libraries.
gcc -fPIC -shared -o libshm.so lib_shared_memory.c
As a caveat
shmctl(segid, IPC_RMID, NULL);
Let's execute it after the attached process becomes 0 and the release is confirmed. If the attached process is executed when it exists, when a new process tries to attach to the shared memory, it will create a new shared memory even though it has the same key. To prevent this, the number of processes attached to the shared memory is managed by placing it as a variable on the shared memory so that the process to detach the shared library at the end can be released.
I didn't understand this, I was adding a release request when creating shared memory, and I wasn't able to attach to shared memory.
that's all.
Recommended Posts