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

Getting Zero in out as value of shared memory variable

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

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

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

参见 test 的示例。 counter.

应该相同
if ((test = (int *) shmat(shmID, 0, 0)) == -1) 
{
   perror("shmat");
   exit(1);
}

如果shm有问题可以在cli里查看,比如shm已经创建,使用命令ipcs查看或者ipcrm shm删除重新初始化:

ipcs shm | grep [your_shm_key or shmid]