shmctl 在 C 中抛出 "cannot allocate memory"

shmctl throws "cannot allocate memory" in C

我有这个代码:

#define SHMSIZE 8388606
int main()
{
    int shmid;
    void *shmPtr;
    char *shm;
    if ((shmid = shmget(IPC_PRIVATE, sizeof(char) * SHMSIZE , IPC_CREAT |        0666)) < 0) {
        perror("shmget");
        exit(1);
    }

    if ((shmPtr = shmat(shmid, NULL, 0)) == (char *) -1) {
       perror("shmat");
       exit(1);
    }
    shm = (char *)shmPtr;
    strncpy(shm, "0\n", 2);

    struct shmid_ds  shmid_ds;
    int rtrn = shmctl(shmid, SHM_LOCK, &shmid_ds);
    if(rtrn < 0) {
        perror("shmctl");
        exit(1);
    }
    else {
        printf("Nailed it\n" );
    }
    return 0;
}

运行它,我得到错误:

shmctl: Cannot allocate memory

为 SHMSIZE 定义较小的值修复了错误,但我发现奇怪的是这个错误是在 "shmctl" 部分抛出的。我的推理告诉我,这个错误应该在 "shmget" 部分抛出。

此代码如何通过 shmget() 调用成功运行?我错过了什么重要的事情吗?

阅读本文,它可能会帮助您解决问题:

   The caller can prevent or allow swapping of a shared memory segment
   with the following cmd values:

   SHM_LOCK (Linux-specific)
             Prevent swapping of the shared memory segment.  The caller
             must fault in any pages that are required to be present
             after locking is enabled.  If a segment has been locked,
             then the (nonstandard) SHM_LOCKED flag of the shm_perm.mode
             field in the associated data structure retrieved by
             IPC_STAT will be set.

   SHM_UNLOCK (Linux-specific)
             Unlock the segment, allowing it to be swapped out.

   In kernels before 2.6.10, only a privileged process could employ
   SHM_LOCK and SHM_UNLOCK.  Since kernel 2.6.10, an unprivileged
   process can employ these operations if its effective UID matches the
   owner or creator UID of the segment, and (for SHM_LOCK) the amount of
   memory to be locked falls within the RLIMIT_MEMLOCK resource limit
   (see setrlimit(2)).

试试这个:

int rtrn = shmctl(shmid, IPC_STAT, &shmid_ds);