将零作为共享内存变量的值

Posted

技术标签:

【中文标题】将零作为共享内存变量的值【英文标题】:Getting Zero in out as value of shared memory variable 【发布时间】:2018-04-23 10:06:22 【问题描述】:

我有一个父程序,它将派生以下子程序并递增、显示、递减和显示变量“test”(最初为 0)15 次。我尝试运行它很多次,看看每隔几行我得到什么输出,但是我不知道我的“测试”变量是如何只显示零,15 次。

    //Include required preprocessors
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

#define SHARED_MEM 1024 //shared memory size

int main(void)

    /* The child process' new program. This program replaces the parent's */
    /* program when 'fork()' is called */
    printf("Process[%d]: child in execution ... \n",getpid());

    int MAX = 15;
    int shmID, shmID2;
    key_t key = 1234, key2 = 2345;
    int *test, *counter;

    shmID = shmget(key, SHARED_MEM, 0666);

    printf("\nShmID: %d", shmID);

    shmID2 = shmget(key2, SHARED_MEM, 0666);

    printf("\nshmID2: %d", shmID2);

    test = (int *) shmat(shmID, 0, 0);
    counter = (int *) shmat(shmID2, 0, 0);

    printf("\ntEST before assignment: %d", *test);
    printf("\nCounter: %d", *counter);

    *test = 0;
    *counter = 1;

    printf("\ntest: %d", *test);
    printf("\nCounter%d", *counter);

    printf("\nAlmost there...");
    if (*counter == 1)
        for(int i=0; i < MAX; i++)
            printf("\MAX: %d", MAX);
            printf("%d", *test);
            *test++;
        
    *counter++; //to enter second condition of second child process
    printf("\nCounter: %d", counter);
    
    else if(*counter == 2)
        for(int j = 0; j < MAX; j++)
        printf("%d", *test);
        *test++;
        
    *counter--;
    

    sleep(1);
    printf("Process[%d]: child terminating ... \n", getpid());

    shmdt(test);
    shmdt(counter);
    return 0;

【问题讨论】:

【参考方案1】:

我可以看到几件事。

    与代码结构无关,我会检查 shmget 和 shmat 中是否有错误: 我会改变

    shmID = shmget(key, SHARED_MEM, 0666) shmID2 = shmget(key2, SHARED_MEM, 0666);

if ( (shmID = shmget(key, SHARED_MEM, 0666)) < 0)  

    perror("shmget"); 
    exit(1); 
  
if ( (shmID2 = shmget(key2, SHARED_MEM, 0666) < 0)  

    perror("shmat");
    exit(1); 


    请注意,您正在创建具有0666 权限但没有IPC_CREAT | IPC_EXCL 的SHM。 我建议您第一次创建时使用IPC_CREAT | IPC_EXCL | 0666 标志。

    与第 1 点一样,我也会检查 shmat 的问题:

参见test 的示例。 counter 应该是一样的。

if ((test = (int *) shmat(shmID, 0, 0)) == -1) 

   perror("shmat");
   exit(1);


你可以在cli中检查shm是否有问题,例如已经创建,使用命令ipcs检查或ipcrm shm删除并重新初始化:

ipcs shm | grep [your_shm_key or shmid]

【讨论】:

以上是关于将零作为共享内存变量的值的主要内容,如果未能解决你的问题,请参考以下文章

volatile 内存语义

从缓存行出发理解volatile变量伪共享False sharingdisruptor

python 归纳 (二十)_多进程数据共享和同步_共享内存Value & Array

Volatile与Synchronized的区别

并发编程:volatile关键字

volatile与synchronized比较