fork call __attribute__((destructor))
Florian Weimer
fw@deneb.enyo.de
Sat Aug 5 07:14:00 GMT 2017
* Yubin Ruan:
> 2017-08-05 2:10 GMT+08:00 Carlos O'Donell <carlos@redhat.com>:
>> On 08/04/2017 01:01 PM, Yubin Ruan wrote:
>>> Hi,
>>> I used to assumed that a function marked with a
>>> "__attribute__((destructor))" would be called after the .so is
>>> unloaded, typically when the program exit. However, I discover that
>>> when I call "fork()" the destructor is also called.
>>>
>>> How could that happen? Is it a bug or something? Am I doing something
>>> wrong? What is the rationale behind that?
>>>
>>> And, is there any way to prevent the destructor being called when
>>> somebody call fork()?
>>
>> Please provide an example program that does this.
>
> /* forklib.c, compile this to the .so file */
> __attribute__((destructor)) {
> printf("Destructor is called\n");
> }
>
> /* main.c, use LD_PRELOAD=/path/to/the/xxx.so to tell the dynamic linker
> * to load the .so file. You will see that the "destructor" is called
> * after fork, in both parent and child
> */
> #include <stdio.h>
> #include <unistd.h>
> int main()
> {
> pid_t pid = fork();
> if(0 == pid) {
> printf("In child process\n");
> }else{
> printf("In parent process\n");
> }
> return 0;
> }
Traditionally, fork does not inhibit any of the process termination
steps. If you call exit in the child or return from main, all the
atexit handlers run. I don't see a reason why we should treat ELF
destructors differently.
You need to call _exit explicitly to inhibit the usual process cleanup
steps.
More information about the Binutils
mailing list