Replacing the close () function on Linux with my own close () function

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?

+6
source share
2 answers

This kind of "replacement" only works for dynamically linked programs.

Any program linked statically to a library that implements close -call cannot replace it.

The latter will take place for every call to close() from the library that implements the original close() . And it also looks like standard file descriptors 0 , 1 and 2 , since closing them is most likely implemented in the same library that is used in the libc implementation.

+2
source

I am surprised that it worked as well as it did!

You are replacing the C library entry for the close () function, not the system call. However, other parts of the C library are still used for these programs. There is probably some direct link to the first three files. Look at the source of any C library that you are using.

+1
source

All Articles