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

Seb picture Seb · Nov 27, 2008 · Viewed 37k times · Source

You can use command lsof to get file descriptors for all running processes, but what I would like to do is to close some of those descriptors without being inside that process. This can be done on Windows, so you can easily unblock some application.

Is there any command or function for that?

Answer

Andreas picture Andreas · Nov 27, 2008

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 cat
7213

$gdb -p 7213

...
lots of output
...

(gdb)

Now you tell gdb to execute close(0):

(gdb) p close(0)

$1 = 0

(gdb) c

Continuing.

Program exited with code 01.
(gdb)

In the first shell I get this output:

cat: -: Bad file descriptor

cat: closing standard input: Bad file descriptor