prctl系统调用设置进程名

1. prctl 系统调用函数

$ man 2 prctl
//prctl - operations on a process
//#include <sys/prctl.h>

int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);

//return 0 on success.  On error, -1 is returned, and errno is set appropriately.

2. prctl设置进程名内核响应

复制代码
SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, unsigned long, arg4, unsigned long, arg5)//kernel/sys.c
{
    ...
    switch (option) {
    ...
    case PR_SET_NAME:
        comm[sizeof(me->comm) - 1] = 0;
        if (strncpy_from_user(comm, (char __user *)arg2, sizeof(me->comm) - 1) < 0)
            return -EFAULT;
        set_task_comm(me, comm);
        proc_comm_connector(me);
        break
    ...
    }
    ...
}
复制代码

可见 arg2 就是要设置的进程名,arg1需要为 PR_SET_NAME,其它参数不用管。此外 prctl() 还可以获取进程名字,设置 timerslack; 此外还有 getcpu() 系统调用,可以查看当前进程运行在哪个CPU上了。

3. 实验程序

复制代码
#include <stdio.h>
#include <unistd.h>
#include <sys/prctl.h>

int main()
{
    int ret = prctl(PR_SET_NAME, "hello_world", NULL, NULL, NULL);
    printf("ret=%d\n", ret);
    while(1) {
        sleep(1);
    }
    return 0;
}
复制代码

测试结果:

复制代码
$ gcc prctl_test.c -o pp
$ ./pp &
[2] 39844
$ ret=0

$ cat /proc/39844/comm 
hello_world
$ ps -AT | grep 39844
 39844  39844 pts/13   00:00:00 hello_world
复制代码

补充:

4. 给线程重命名

复制代码
int create_touch_handler()
{
    pthread_t handlerThread;
    pthread_attr_t attr;

    pthread_attr_init(&attr);
    pthread_create(&handlerThread, &attr, TouchHandler, NULL);
    pthread_setname_np(handlerThread, "PowerTouch"); //给线程重命名

    return 0;
}
复制代码

 

posted on   Hello-World3  阅读(1240)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示