Reputation: 4074
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.
Upvotes: 0
Views: 1569
Reputation: 82026
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()
.
#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();
}
#include <unistd.h>
int main() {
fork();
fork();
return 0;
}
[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
Upvotes: 2