summaryrefslogtreecommitdiff
path: root/lib/shmem.cpp
blob: 113babfc56bb4ecd2de5cadaa2f18cef7a48aa85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "NativeSharedMemory.hpp"
#include "DecoderWorkerLock.hpp"
#include <memory>
#include <cstdio>
#include <exception>

namespace
{
  // Release the mapping before the lifetime lock, after all Fortran cleanup.
  std::unique_ptr<DecoderWorkerLock> worker_lock;
  NativeSharedMemory shmem;
}

extern "C"
{
  bool shmem_lock_worker (char const * path) noexcept
  {
    try
      {
        worker_lock.reset (new DecoderWorkerLock {path});
        if (worker_lock->tryLock ()) return true;
        std::fprintf (stderr, "Decoder worker lock: %s\n", worker_lock->errorString ().c_str ());
      }
    catch (...)
      {
        std::fputs ("Decoder worker lock: initialization failed\n", stderr);
      }
    return false;
  }

  bool shmem_attach (char const * name) noexcept
  {
    try
      {
        if (shmem.attach (name)) return true;
        std::fprintf (stderr, "Decoder shared memory: %s\n", shmem.errorString ().c_str ());
      }
    catch (std::exception const& error)
      {
        std::fprintf (stderr, "Decoder shared memory: %s\n", error.what ());
      }
    catch (...)
      {
        std::fputs ("Decoder shared memory: unexpected attachment failure\n", stderr);
      }
    return false;
  }
  std::size_t shmem_size () noexcept {return shmem.size ();}
  void * shmem_address () noexcept {return shmem.data ();}
}