Is fork() hook ever possible?

Daniel Eischen deischen at freebsd.org
Tue Sep 16 16:50:55 UTC 2008


[ Trimmed ]

On Tue, 16 Sep 2008, Andrey Chernov wrote:

> On Tue, Sep 16, 2008 at 11:36:03AM -0400, Daniel Eischen wrote:
>
>> Well, you could speed up getpid() by having libc wrap all fork()
>> variants.  The idea is that getpid() would only call __sys_getpid()
>> the first time it was called and then only after a fork().  It
>> would return the saved process id for all other cases.
>
> Yes, speeding up getpid() by caching its pid is nice idea.
> But I am completely unaware how to create syscall wrappers inside libc. :(
> I think about something like that:
>
> __weak_reference(_fork, fork);

I think you'll have to implement it as __fork() in libc, with
_fork and fork both being weak references to __fork() in libc.  The
thread libraries will have to call __fork() instead of __sys_fork()
by implementing "fork" as _fork() and providing a weak reference
from fork to _fork.  You can see wait() as an example.

Probably rfork() and vfork() will need to be handled as well,
though I don't think that the thread libraries care about these.

> But how it will coexists with the same __weak in thread/thr_fork.c ?
> Are some threading locks required in this code?

I think you can do it without locks.  After a fork() you are
single threaded so you can easily set/clear __cur_thread.
Otherwise, the worst case is that multiple threads will call
_sys_getpid() simultaneously the first time, but as long as
you atomically update __cur_thread, it won't matter - each
thread will have retrieved the same exact process id so it
is okay if they all update __cur_thread.

 	pid_t
 	__getpid(void)
 	{

 		if (__cur_thread != -1)
 			return (__cur_thread);

 		atomic_set_32(&__cur_thread, __sys_getpid());
 			return (__cur_thread);
 	}
 	__weak_reference(__getpid, getpid);
 	__weak_reference(__getpid, _getpid);

Or something like that...

-- 
DE


More information about the freebsd-current mailing list