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

标签 c memory-management fork ipc shared-memory

我有一个父程序,它将 fork 以下子程序并递增、显示、递减并显示变量“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 创建 SHM特权但没有IPC_CREAT | IPC_EXCL 。 我建议您第一次创建时使用 IPC_CREAT | IPC_EXCL | 0666旗帜。
  • <小时/>
  • 与第一点相同,我还将检查 shmat 的问题:
  • 参见 test 的示例。 counter 应该是相同的.

    if ((test = (int *) shmat(shmID, 0, 0)) == -1) 
    {
       perror("shmat");
       exit(1);
    }
    
    <小时/>

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

    ipcs shm | grep [your_shm_key or shmid]
    

    关于c - 将零输入输出作为共享内存变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49978401/

    相关文章:

    不使用 sprintf() 将 float 转换为字符串

    c - 关于客户端/服务器 echo 程序的上一个问题的后续

    fork - 在 fork() 中,哪个将首先运行,父级还是子级?

    java - 如果在没有任何选项的情况下运行 JVM,对内存使用有何影响?

    c - 如何在后台进行更新过程

    c - SHA256 摘要在数组初始值设定项和字符串之间有所不同

    c - 逆向工程方程将密文转换为明文

    c - 鹅卵石 : How to pass an integer as callback_data with app_timer_register?

    c++ - SomeClass* initialEl = new SomeClass[5];

    c++ - 使用 C++ 函数参数的连续内存保证