Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...