Some colleagues asked me: when using the cp command, if the file to be overwritten (binary executable file) is running, the cp will report an error, how does the cp command know that the file is being executed? Label: Linux cp
My first thought was: Maybe ioctl can check the file. Unfortunately, I guess it is wrong. I checked the cp source code. if a file is running and another process is open again to obtain the write permission, the open itself will fail and return-1, errno is ETXTBSY.
So why can cp-f be used? Because cp-f deletes the target file (the file to be overwritten) and rename the source file as the target file name.
From the kernel code, when a binary file is run
Sys_execve ()
Do_execve ()
Open_exec ()
Deny_write_access ()
Here, deny_write_access reduces the I _writecount member of the inode file by 1. Generally, the I _writecount value is changed to-1 (initially 0)
At this time, another process wants to open in write mode:
Do_sys_open ()
Do_filp_open ()
Path_openat ()
Do_last ()
Nameidata_to_filp ()
_ Dentry_open ()
_ Get_file_write_access ()
Get_write_access ()
Get_write_access returns the-ETXTBSY