根据pid获取进程名

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void get_process_name_by_pid(int pid, char *name)
{
    char buf[256] = {0};
    char path[256] = {0};

    sprintf(buf, "/proc/%d/exe", pid);
    readlink(buf, path, sizeof(path));

    char *filename = basename(path);
    strcpy(name, filename);
}

C语言变长数组

C99标准才有的特性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void test_vla(const char *str)
{
    int len = strlen(str);

    char a[len + 1];
    memset(a, 0, sizeof(a));

    strcpy(a, str);

    printf("%s\n", a);
}

确保路径存在

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool besure_path(const char *pathname) {
    int len = strlen(pathname);

    char buffer[len + 1];
    memset(buffer, 0, sizeof(buffer));

    strcpy(buffer, pathname);

    for (int i = 0; i < len; ++i) {
        if (buffer[i] == '/') {
            buffer[i] = 0;

            if (access(buffer, F_OK) < 0) {
                if (mkdir(buffer, 0755) < 0) {
                    return false;
                }
            }

            buffer[i] = '/';
        }
    }

    return true;
}

计算一个数字二进制格式1的个数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int count_bit(int n) {
    int count = 0;

    while (n != 0) {
        ++count;
        n &= n - 1;
    }

    return count;
}