Re: how does fork() work?

Systemkennung Linux (linux@mailhost.uni-koblenz.de)
Tue, 4 Mar 1997 22:01:33 +0100 (MET)


Hi,

> > I want to write a debugging fork (i.e. one that prints and stops after forking).
> >
> > I want to use LD_PRELOAD to wrap around fork...so I need a more complicated C
> > function called fork, eventually invoking the syscall.
> >
> > I'm a bit confused with the libc architecture for syscalls, what headers
> > (sysdep?) do I need to pull out of the tree and place around an application
> > for this?
> >
> > What I eventually want is:
> >
> >
> > fork()
> > {
> > fancy stuff;
> >
> > result = system entry point fork()
> >
> > if(child) {
> > printf();
> > pause();
> > }
> > return result;
> >
> > }
> >
> >
>
> The simpliest solution would be to call dlsym(RTLD_NEXT, "fork") (in <dlfcn.h>)
> and link your preload library with -ldl. Free compatibility with Solaris :)

While this is a correct solution it's plain overkill. For just wrapping
a call to a subroutine you should better use the --wrap option of ld.
>From the ld docs:

`--wrap SYMBOL'
Use a wrapper function for SYMBOL. Any undefined reference to
SYMBOL will be resolved to `__wrap_SYMBOL'. Any undefined
reference to `__real_SYMBOL' will be resolved to SYMBOL.

This can be used to provide a wrapper for a system function. The
wrapper function should be called `__wrap_SYMBOL'. If it wishes
to call the system function, it should call `__real_SYMBOL'.

Here is a trivial example:

void *
__wrap_malloc (int c)
{
printf ("malloc called with %ld\n", c);
return __real_malloc (c);
}

If you link other code with this file using `--wrap malloc', then
all calls to `malloc' will call the function `__wrap_malloc'
instead. The call to `__real_malloc' in `__wrap_malloc' will call
the real `malloc' function.

You may wish to provide a `__real_malloc' function as well, so that
links without the `--wrap' option will succeed. If you do this,
you should not put the definition of `__real_malloc' in the same
file as `__wrap_malloc'; if you do, the assembler may resolve the
call before the linker has a chance to wrap it to `malloc'.

Free compatibility with GNU :-)

Ralf