I am trying to provide my own implementation of the close() function on Linux. What for? Because I just found out that you can do it, and it sounds fun.
Here is myclose.c:
#include <stdio.h> int close(int fd) { printf("Closing fd: %d\n", fd); return 0; }
Here is my makefile:
all: myclose.so my-close.so %.so: %.o gcc -shared -o $@ $< %.o:%.c gcc -c -fPIC -o $@ $< clean: rm -f *.so *.o
After compilation, I run:
export LD_PRELOAD=`pwd`/myclose.so
Then I run:
cat myclose.c
The output I get is:
#include <stdio.h> int close(int fd) { printf("Closing fd: %d\n", fd); return 0; } Closing fd: 3
Hooray! Does it work correctly? Nearly. cat calls close() more than once, but we only see one line of output. According to strace (and common sense), close() should be called for file descriptors 1 and 2. If I run cat * and cat all the files in the directory, I see "Close fd: 3", "Close fd: 4" and so on. .d. Up to the last file in the directory. Since all of these file descriptors are larger than 2, I thought that there might be a problem closing special file descriptors (stdout and stderr). However, when I run ls , I see only regular output and the lines “Close fd:”, which means that it does not work for ls , even if strace shows close(3) when ls starts.
Any ideas on what might be wrong?
source share