The lsof command displays the names of the open files currently. How to write a script that closes all these files? What is the general command / operation used in scripts to close files?

    2 answers 2

    Do you want to close the file descriptor of someone else's process? This is a strange desire: you will most likely cause errors in the process in which this handle is open. But if you really want it and you clearly understand what you are doing, you can use my solution using gdb (I didn’t think of anything better):

     #!/bin/sh pid=$1 fd=$2 commands=$(mktemp "gdb.XXXXXXXXXX") echo -e "attach $pid\np close($fd)" > $commands gdb -batch -x $commands > /dev/null status=$? rm $commands exit $status 

    This script starts gdb, attaches to the process with the pid passed in the first argument, and closes the handle passed in the second argument. The script must be run with superuser rights.

    An example of use.

     $ cat test.c #include <stdio.h> int main() { FILE* f = fopen("foo.txt", "w"); while (1); return 0; } $ gcc test.c -o test $ ./test & $ lsof 2>/dev/null | grep "foo.txt" test 5904 dzhioev 3w REG 252,0 0 10884489 /home/dzhioev/ foo.txt $ sudo ./close_fd.sh 5904 3 $ lsof 2>/dev/null | grep "foo.txt" $ #nothing 
    • Perhaps this is a good solution, but not at all what I need. - Dariallah
    • Well then write what you need. I wrote what you asked for. - dzhioev pm
    • @dzhioev cool. - Costantino Rupert

    I really hope I misunderstood, but closing ALL files shown after using lsof is equivalent to shutting down the system ( shutdown -h now ).

    • Not, not all files, but the current is specific. they hang in the memory and interfere with others. - Dariallah
    • 2
      So maybe you need to understand how to interrupt the process that opened a particular file? - skegg
    • Maybe yes. Only one process works with several files, and if you kill the process, then all files will close, not specific ones. - Darialla
    • Well, imagine. The process has open file descriptors. You find ways to close them (all or only specific). Next, the process tries to access these descriptors. An exceptional situation arises in the normal program, and anything can happen to the process, up to its closing (at best) or incorrect work. AND? - skegg
    • But how can I close only specific files so that incorrect work does not occur? that is my question - Darialla