将Zero作为共享内存变量的值取出

问题描述 投票:0回答:1

我有一个父程序,它将分叉以下子程序并递增,显示,减少并显示变量'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;
}
c memory-management fork ipc shared-memory
1个回答
1
投票

我可以看到几件事。

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

  1. 请注意,您使用0666权限创建SHM但没有IPC_CREAT | IPC_EXCL。我建议你第一次用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]
© www.soinside.com 2019 - 2024. All rights reserved.