简体   繁体   中英

how to detect read from deleted mmap file?

I have process1 create shared memory by the following steps in RedHat 6.5 :

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 :

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 :

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 ?

Edit :

Is it ok to use stat in shared memory file ? process2 can detect file deleted by :

    #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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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