mlock() vs shmctl(SHM_LOCK) on Linux?

linux, memory

Solution

First of all, mlock() is the syscall to lock process memory in the RAM, and shmctl(X,SHM_LOCK,Y) is used to do shared (IPC) memory, which requires more control from all the producers and consumers, so, that is why mlock() syscall is much easier as:

     int mlock(const void *addr, size_t len);

While shmctl is much more complex to operate, as:

   int shmctl(int shmid, SHM_LOCK, struct shmid_ds *buf);

Where: The buf argument is a pointer to a shmid_ds structure, defined in as follows:

       struct shmid_ds {
           struct ipc_perm shm_perm;    /* Ownership and permissions */
           size_t          shm_segsz;   /* Size of segment (bytes) */
           time_t          shm_atime;   /* Last attach time */
           time_t          shm_dtime;   /* Last detach time */
           time_t          shm_ctime;   /* Last change time */
           pid_t           shm_cpid;    /* PID of creator */
           pid_t           shm_lpid;    /* PID of last shmat(2)/shmdt(2) */
           shmatt_t        shm_nattch;  /* No. of current attaches */
           ...
       };

Problem

What is the difference between calling `mlock()` on some memory and calling `shmctl(SHM_LOCK)` on that same memory? These are the only differences I can ascertain: - `mlock()` guarantees that all locked pages are loaded when it returns. `shmctl(SHM_LOCK)` prevents swapping, but doesn't proactively load non-resident pages. - `shmctl(SHM_LOCK)` can only be used on shared memory segments. - `shmctl(SHM_LOCK)` sets an extra flag (`SHM_LOCKED`) on the permissions of the shared memory segment. Are there other differences? In particular, is there any reason not to use `mlock()` on a shared memory segment?

Original source