简体   繁体   English

如何编辑linux内核文件?

[英]How to edit linux kernel files?

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). 我正在使用fork函数创建一个子进程,我想以一种方式编辑它,无论何时调用它都应该打印是否创建了进程,(我这样做只是为了练习,我知道它是没用)。

What I have researched is this that fork function is defined in a file named fork.c which is in linux/kernel. 我研究的是fork函数是在一个名为fork.c的文件中定义的,它位于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 ? 我不知道我的ubuntu操作系统中的这个文件夹在哪里,如果我以某种方式访问​​fork.c那么操作系统允许我编辑?

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. 我只想以一种在创建进程时打印的方式编辑fork.c.

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. Plzz忽略了我所说过的任何无用的东西,如果你能给我答案的步骤来修改fork.c然后使用它会很棒。

So Linux has a helpful trick that you can use to do this in a far easier way. 因此Linux有一个有用的技巧,你可以用它来做到这一点的容易的方式。 It's called LD_PRELOAD . 它被称为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() . 这个共享库将能够在调用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM