1. List all Open Files with lsof Command
> lsof
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
init 1 root cwd DIR 253,0 4096 2 /
init 1 root rtd DIR 253,0 4096 2 /
init 1 root txt REG 253,0 145180 147164 /sbin/init
init 1 root mem REG 253,0 1889704 190149 /lib/libc-2.12.so
FD
column stands for File Descriptor
, This column values are as below:-
cwd
current working directory-
rtd
root directory-
txt
program text (code and data)-
mem
memory-mapped fileTo get the count of open files you can use
wc -l
with lsof
like as follow:lsof | wc -l
2. List User Specific Opened Files
lsof -u alireza
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 1838 alireza cwd DIR 253,0 4096 2 /
sshd 1838 alireza rtd DIR 253,0 4096 2 /
#linux #sysadmin #lsof #wc #file_descriptor
I have a script that checks a source folder for new files in case there are files in the source folder, it will move those files to destination.
The problem I encountered recently was that files are huge and it may be in the middle of the copying into source by another process so my script tries to move an incomplete file to a destination. Let's say the file is 4GB in size and just only 1GB of the file has been copied. I have to wait until file is 4GB and other handler using that file, then I should safely move the file.
You can use
#linux #sysadmin #lsof #grep
The problem I encountered recently was that files are huge and it may be in the middle of the copying into source by another process so my script tries to move an incomplete file to a destination. Let's say the file is 4GB in size and just only 1GB of the file has been copied. I have to wait until file is 4GB and other handler using that file, then I should safely move the file.
You can use
lsof
command in order to check which processes are using the source file:if [[ `lsof -- /var/my-folder/my-big-file.tar.gz` ]]
then
echo "File is being used by a process."
exit 1
fi
NOTE:
you can give file directly to lsof
using --
or you can use grep command as follow:lsof | grep /var/my-folder/my-big-file.tar.gz
NOTE2:
if you are in a loop use break
instead of exit
.NOTE3:
if you get command not found
, install it using apt-get install lsof
#linux #sysadmin #lsof #grep