Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

c - Behaviour of shm_unlink

I have the following code snippet :

fd_mem = shm_open(MEM_NAME , O_RDWR | O_CREAT | O_EXCL , 0600);

//Why do we use unlink before having mmaped ? 
shm_unlink ( MEM_NAME );

ftruncate (fd_mem , mem_size)
    
plateau = (char*) mmap(NULL , mem_size , PROT_READ | PROT_WRITE , MAP_SHARED , fd_mem , 0);

My question is: why do we use "unlink" before having mapped the file into the virtual memory of the process? I'm confused as to how shm_unlink() works in that regard. I would think it deletes the file making fd_mem unusable but it doesn't.

question from:https://stackoverflow.com/questions/65860154/behaviour-of-shm-unlink

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Opening a file or a shared memory segment increments a reference counter on the underlying "kernel object". The deletion operation, deletes the name of the object but does not decrement the reference counter. As long the reference counter is bigger than 0, the object is not destroyed.

The deletion of the object after opening it, is for the automatic cleanup when the process terminates voluntarily (exit) or unvoluntarily (receipt of a signal) : the termination triggers a "close" operation which decrements the reference counter. When the latter drops to 0, the object disappears because the deletion operation completes as well.

Without this tricks, an process may terminate without doing any cleanup and consequently leaves "garbage" entries in the file system.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...