0

I am working of fork function which creates a child process, I want to edit it in a way that whenever it is called it should print whether the process is created or not, (I am doing it just for practice, I know it is of no use).

What I have researched is this that fork function is defined in a file named fork.c which is in linux/kernel. I don't know that where is this folder in my ubuntu OS and also if I somehow get access to fork.c then will OS allow me to edit ?

I have also read that for this purpose I have to download another kernel and then edit the downloaded one with disturbing original (which is a headache).

I only want to edit fork.c in a way that it prints if a process is created or not.

Plzz ignore any useless stuff i have said, it would be great if you could give me the answer in steps to modify fork.c and then use it.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117
mfs
  • 3,984
  • 6
  • 32
  • 51
  • It sounds like you are already aware of the process for doing this, and no, there is not a shortcut. This has been covered here many times before so it will most likely be closed as a duplicate. – Chris Stratton Mar 31 '14 at 14:02
  • Try `man strace`; `strace` is a program that traces system calls such as `fork()`. There is no need to modify the Linux source. You probably have `strace` installed; or run `sudo apt-get install strace`. – artless noise Mar 31 '14 at 15:05

1 Answers1

2

So Linux has a helpful trick that you can use to do this in a far easier way. It's called LD_PRELOAD.

Using this trick, we can create a shared library that we inject into another process. This shared library will be able to run code before and after the call to fork().

Shared Library Code

#define _GNU_SOURCE

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dlfcn.h>

static pid_t (*real_fork)(void);

pid_t fork(void)
{
    printf("Fork is called\n");
    if (real_fork == NULL)
        real_fork = (pid_t (*)(void))dlsym( RTLD_NEXT, "fork" );
    return real_fork();
}

Demo Application Code

#include <unistd.h>

int main() {
    fork();
    fork();

    return 0;
}

Showing how to put it all together

[10:19am][wlynch@apple preload] gcc -Wall test.c -o test
[10:19am][wlynch@apple preload] gcc -shared -ldl -fPIC fork.c -o fork.so 
[10:20am][wlynch@apple preload] ./test
[10:20am][wlynch@apple preload] env LD_PRELOAD=/tmp/preload/fork.so ./test
Fork is called
Fork is called
Fork is called
Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173