How to close a file descriptor from another process in unix systems How to close a file descriptor from another process in unix systems bash bash

How to close a file descriptor from another process in unix systems


I don't know why you are trying to do this, but you should be able to attach to the process using gdb and then call close() on the fd. Example:

In one shell: cat

In another shell:

$pidof cat7213$gdb -p 7213...lots of output...(gdb)

Now you tell gdb to execute close(0):

(gdb) p close(0)$1 = 0(gdb) cContinuing.Program exited with code 01.(gdb)

In the first shell I get this output:

cat: -: Bad file descriptorcat: closing standard input: Bad file descriptor


I don't think so but lsof gives you the PID of the process that has opened the file, so what you can do is entirely kill the process or at least send a signal to let it exit.


In Windows you can use a program to do it because someone wrote a program that inserts a device driver into the running kernel to do it. By the way it can be dangerous to do this, because after you close a handle that a broken application was using, the application doesn't know that the handle was closed, and when the application opens some other unrelated object it doesn't know that the same handle might now refer to some other unrelated object. You really want to kill the broken application as soon as possible.

In Linux surely you can use the same kind of technique. Write a program that inserts a module into the running kernel. Communicate with the module and tell it which handles to close. It will be equally dangerous to do so.