在 Linux 系统中,/proc 目录下存放了系统内核运行时产生的大量进程和系统信息,其中 /proc/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
 //向 /proc/<pid>/stat 文件中添加值的函数
void AddValueToProcStat(int pid, int value)
{
    char stat_file[50];
    sprintf(stat_file, "/proc/%d/stat", pid);  //定义 /proc/<pid>/stat 文件路径
    int fd = open(stat_file, O_RDWR);  //以读写方式打开文件
    if (fd == -1) {
        printf("open file failed.\n");
        return;
    }
    char buf[1024];
    int len = read(fd, buf, sizeof(buf));  //读取文件内容
    if (len <= 0) {
        printf("read file failed.\n");
        close(fd);
        return;
    }
    char *ptr = strstr(buf, ") ");  //找到文件内容中的') ”位置
    if (ptr == NULL) {
        printf("parse file failed.\n");
        close(fd);
        return;
    }
    ptr += 2;  //指针后移两个字节,指向统计信息的起始位置
    //将值转换成字符串,并插入到统计信息中
    char str[50];
    snprintf(str, sizeof(str), "%d ", value);
    memmove(ptr + strlen(str), ptr, len - (ptr - buf));
    memcpy(ptr, str, strlen(str));
    lseek(fd, 0, SEEK_SET);
    write(fd, buf, strlen(buf));  //将修改后的文件内容写入文件中
    close(fd);
}
该函数以进程号 pid 和要添加的值 value 为参数,首先根据进程号构造 /proc/
pid (comm) state ppid ...
其中,pid