代码之家  ›  专栏  ›  技术社区  ›  Andrej

shmctl在C中抛出“无法分配内存”

  •  0
  • Andrej  · 技术社区  · 7 年前

    我有这个代码:

    #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;
    }
    

    运行它,我得到了错误:

    这段代码如何通过shmget()调用成功运行?我错过重要的东西了吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Kanji Viroja    7 年前

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

       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);