简体   繁体   English

如何检测从已删除的mmap文件读取?

[英]how to detect read from deleted mmap file?

I have process1 create shared memory by the following steps in RedHat 6.5 : 我通过RedHat 6.5中的以下步骤来创建process1共享内存:

if((shm_fd1 = shm_open(sharedfile1, (O_CREAT | O_EXCL | O_RDWR),
                   (S_IREAD | S_IWRITE))) > 0 ) {
    printf("shared memory shm_fd1 created !! \n") ;
}
ftruncate(shm_fd1, sizeof(struct_order)*iGlbCallCnt );
if((ptrsharedCall = (struct_order*) mmap(0, sizeof(struct_order)*iGlbCallCnt , (PROT_READ | PROT_WRITE),
               MAP_SHARED, shm_fd1, 0)) == MAP_FAILED) 
{
    printf("shared memory shm_fd1 mmap error , errno=(%d)\n",errno) ;
    printf("try to remove /dev/shm/ file \n") ;
    exit(0) ;
}

The procees2 read data from what process1 create : procees2从process1创建的数据中读取数据:

if((shm_fd1 = shm_open(sharedfile1, (O_RDWR),
                   (S_IREAD | S_IWRITE))) < 0 ) {
    printf("shared memory shm_fd1  error  !! \n") ;
    exit(0) ;
}
ftruncate(shm_fd1, sizeof(struct_order)*iGlbCallCnt );
if((ptrsharedCall = (struct_order*) mmap(0, sizeof(struct_order)*iGlbCallCnt , (PROT_READ | PROT_WRITE),
               MAP_SHARED, shm_fd1, 0)) == MAP_FAILED)
{
    printf("shared memory shm_fd1 mmap error , errno=(%d)\n",errno) ;
    printf("try to remove /dev/shm/ file \n") ;
    exit(0) ;
}

It works fine , but I like to inform process2 while process1 delete the shared memory file by : 它工作正常,但我想通知process2,而process1通过以下方式删除共享内存文件:

sprintf(filenm1,"%s%s","/dev/shm/",sharedfile1) ;
unlink(filenm1);

So far I have no idea how process2 to detect that shared memory file is already deleted ,any idea ? 到目前为止,我不知道如何process2来检测该共享的内存文件已被删除,任何想法吗?

Edit : 编辑:

Is it ok to use stat in shared memory file ? 在共享内存文件中使用stat可以吗? process2 can detect file deleted by : process2可以检测到通过以下方式删除的文件:

    #include <sys/stat.h>

    if(stat(filenm1,&sts) < 0)
    {
        printf("(%s) deleted \n",filenm1) ;
        exit(0)  ;
    }

It seems like you're trying to get a notification in one process when another one exits or otherwise decides it's done communicating. 似乎您正在尝试在一个进程中获得通知,而另一个进程退出或以其他方式确定已完成通信。 Rather than trying to communicate this bit of state via the same shared memory IPC, you can do it easily by making a good old TCP connection between the two processes. 您可以通过在两个进程之间建立良好的旧TCP连接来轻松实现此状态,而不必尝试通过相同的共享内存IPC来传达此状态。 Then when one stops or closes the connection, the other will be notified, and this notification is guaranteed by the operating system (though it may take a bit of time to arrive). 然后,当其中一个停止或关闭连接时,将通知另一个,该通知由操作系统保证(尽管可能需要一些时间才能到达)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM