Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <dlfcn.h>
- #include <semaphore.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- //#define DEBUG
- #ifdef DEBUG
- #define DEBUG_PRINT(x) printf x;
- #else
- #define DEBUG_PRINT(x) ;
- #endif
- typedef struct {
- sem_t request_ready;
- sem_t response_ready;
- char func_name[20];
- double value;
- double result;
- } shared_data_t;
- typedef double (*dd_func_t)(double);
- const char SHM_NAME[] = "/maximmum_shm";
- enum { SHM_PERMS = 0644 };
- void prepare_shared_data(shared_data_t* data) {
- memset(data, 0, sizeof(shared_data_t));
- sem_init(&data->request_ready, 1, 0);
- sem_init(&data->response_ready, 1, 0);
- }
- int main(int argc, char** argv)
- {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <library name>", argv[0]);
- return 1;
- }
- void* lib = dlopen(argv[1], RTLD_NOW);
- if (!lib) {
- fprintf(stderr, "Error on dlopen: %s\n", dlerror());
- return 1;
- }
- const size_t page_size = sysconf(_SC_PAGESIZE);
- int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, SHM_PERMS);
- const size_t needed_size = sizeof(shared_data_t);
- const size_t shm_size = (needed_size % page_size == 0 ?
- needed_size :
- (needed_size / page_size + 1) * page_size);
- ftruncate(shm_fd, shm_size);
- shared_data_t* data =
- mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
- prepare_shared_data(data);
- sem_t* request_ready_sem = &data->request_ready;
- sem_t* response_ready_sem = &data->response_ready;
- printf("%s\n", SHM_NAME);
- fflush(stdout);
- do {
- DEBUG_PRINT(("1: sem_wait...\n"));
- sem_wait(request_ready_sem);
- DEBUG_PRINT(("1: sem waited\n"));
- if (data->func_name[0] == '\0') {
- DEBUG_PRINT(("1: func_name is empty, exiting...\n"));
- break;
- }
- void* sym = dlsym(lib, data->func_name);
- if (!sym) {
- fprintf(stderr, "Error on dlsym: %s\n", dlerror());
- break;
- }
- dd_func_t func = sym;
- data->result = func(data->value);
- sem_post(response_ready_sem);
- DEBUG_PRINT(("1: sem posted\n"));
- } while (data->func_name[0] != '\0');
- sem_destroy(response_ready_sem);
- sem_destroy(request_ready_sem);
- munmap((void*)data, shm_size);
- close(shm_fd);
- shm_unlink(SHM_NAME);
- dlclose(lib);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement