0%

times

  1. bash built-in
1
times
  1. function
1
2
3
#include <sys/times.h>

clock_t times(struct tms *buf);

malloc/free

See this example

1
char ** backtrace_symbols (void *const *buffer, int size) 

The return value of backtrace_symbols is a pointer obtained via the malloc function, and it is the responsibility of the caller to free that pointer. Note that only the return value need be freed, not the individual strings.

Question: Why does it say “only the return value need be freed, not the individual strings”?

Let us observe the defintion of the malloc/free functions first:

1
2
void *malloc( size_t size );
void free( void *ptr );

free takes a void* pointer to deallocate the memory, it doesn’t care what type it is, even if it is a multi-level pointer. It means that malloc has stored the memory size in some place and free will find it beforing deallocate the memory.

Let us return the question. The memory pointer returned by backtrace_symbols is the char** type, it must be a whole block contigunous memory using malloc and might be enforced to be transformed as char** pointer when returing. So when we free the memory block, the Linux kernel find its actual memory size and deallocate it.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
char** strings = (char**)malloc(3 * sizeof(char*) + 3 * 50); // assuming a maximum 50 characters per sentence
char* block = (char*)(strings + 3);
char* s1 = strcpy(block, "The first sentence"); block += strlen(s1) + 1;
char* s2 = strcpy(block, "The second sentence"); block += strlen(s2) + 1;
char* s3 = strcpy(block, "The third sentence");
strings[0] = s1;
strings[1] = s2;
strings[2] = s3;
for(int i = 0; i < 3; ++i) {
printf("%s\n", strings[i]);
}
free(strings); // deallocate all memory at once

return 0;
}

More elegant but less economical code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
char** strings = (char**)malloc(3 * sizeof(char*) + 3 * 50);
char* block = (char*)(strings + 3);
for(int i = 0; i < 3; ++i) {
strings[i] = block + i * 50; // Assuming a maximum of 50 characters per sentence
}
strcpy(strings[0], "The first sentence");
strcpy(strings[1], "The second sentence");
strcpy(strings[2], "The third sentence");

for(int i = 0; i < 3; ++i) {
printf("%s\n", strings[i]);
}

free(strings); // deallocate all memory at once

return 0;
}

Reference

shuf

cut

tr

lp

sort

Options:

-t, --field-separator=SEP
    use SEP instead of non-blank to blank transition

-k, --key=POS1[,POS2]
    start a key at POS1 (origin 1), end it at POS2 (default end of line)

-h, --human-numeric-sort
    compare human readable numbers (e.g., 2K 1G)

-n, --numeric-sort
    compare according to string numerical value

nproc

print the number of processing units avaiable.

od / xxd / hexdump

read the binary file.

Notes: byte order

1
2
3
4
5
$ echo -n "ABCD" | xxd
00000000: 4142 4344 ABCD
$ echo -n "ABCD" | hexdump
0000000 4241 4443
0000004

Reference

comm / diff / tkdiff / cmp

Can be used to compare binary or non-binary files.

comm

compare two sorted files line by line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ cat file1.txt 
apple
banana
cherry

$ cat file2.txt
banana
cherry
date
erase

$ comm file1.txt file2.txt
apple
banana
cherry
date
erase

The file must be sorted before using the comm command. Otherwise it will complain that:

comm: file 1 is not in sorted order

and cannot work correctly. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ cat file1.txt 
apple
cherry
banana

$ cat file2.txt
banana
cherry
date
erase

$ comm file1.txt file2.txt
apple
banana
cherry
comm: file 1 is not in sorted order
banana
date
erase
comm: input is not in sorted order

diff

Syntax:

diff -u file1 file2

Options:

-e, --ed
    output an ed script

-u, -U NUM, --unified[=NUM]
    output NUM (default 3) lines of unified context
    (that is, print NUM lines before and after the difference line)

tkdiff

Use a GUI to display the differences.

cmp

Prints less information comparing to diff.

Syntax:

cmp file1 file2

ed/vim/sed/awk

列表初始化

struct/union/array默认支持列表初始化。

Struct and union initialization
Array initialization

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
// #include <initializer_list>
using namespace std;

class A {
public:
int x, y, z; // 注意:数据成员必须是public的。
void print() {
cout << x << " " << y << " " << z << endl;
}
};

class B {
public:
vector<int> vec_;
int x_;
void print() {
cout << "vec_={ ";
for (int x : vec_) {
cout << x << " ";
}
cout << "}, x_=" << x_ << endl;
}
};

class C {
public:
vector<int> vec_;
void print() {
cout << "vec_={ ";
for (int x : vec_) {
cout << x << " ";
}
cout << "}" << endl;
}
};

int main() {
// C++会构造一个列表初始化的默认构造函数,
// 以下(1)和(2)都是调用这个默认构造函数。
A a1{1,2,3}; // (1) 列表初始化
A a2({4,5,6}); // (2) 同(1)
a1.print();
a2.print();

B b1{{1,2,3}, 4}; // 内部的"{1,2,3}"用于构造vec_,"4"用于初始化x_
b1.print();

// C C1{1,2,3}; // (1) 这里会报错"error: too many initializers for ‘C’",
// // 因为C只有一个数据成员vec_,这里却传入了3个参数
C c2{{1,2,3}}; // (2) 其中,内部的"{1,2,3}"用于构造vec_,外层的"{}"用于对c2本身进行构造
c2.print();

return 0;
}

std::initializer_list

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
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
#include <initializer_list>
using namespace std;

struct A {
int x, y, z;

A(initializer_list<int> il) {
initializer_list<int>::iterator it = il.begin();
x = *it++;
y = *it++;
z = *it++;
}

void print() {
cout << x << " " << y << " " << z << endl;
}
};

struct B {
vector<int> vec;

B(initializer_list<int> il) {
vec = il; // 用initializer_list初始化vector
}

void print() {
cout << "{ ";
for (int x : vec) {
cout << x << " ";
}
cout << "}" << endl;
}
};

int main() {
A a{1,2,3};
a.print();

B b{4,5,6};
b.print();

return 0;
}

中括号

  1. [ ]和test是bash的内部命令,[[ ]]是shell的条件判断关键字。

    1
    2
    3
    4
    5
    6
    $ type [
    [ is a shell builtin
    $ type test
    test is a shell builtin
    $ type [[
    [[ is a shell keyword
  2. [ ]和test是等价的,用于评估条件表达式。可以使用man [或help [查阅帮助文档。

    1
    2
    3
    4
    5
    6
    $ help [
    [: [ arg... ]
    Evaluate conditional expression.

    This is a synonym for the "test" builtin, but the last argument must
    be a literal `]', to match the opening `['.
  3. [[ ]]关键字可以屏蔽shell特殊符号,比如&&、||、>和<可以被认为是条件判断符而不是重定向符。

  4. [ ]中使用-a和-o表示逻辑与和逻辑或,[[ ]]中则使用&&和||。

小括号

  1. $()用于命令替换。
  2. 双小括号(( )):在比较过程中使用高级数学表达式。

大括号

请阅读:All about {Curly Braces} in Bash

  1. ${}用于引用变量。

    与$var相比,${var}是一种消除歧义的措施,比如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $ var=abc
    $ vartest=ABC
    # $var引用变量'var'
    $ echo $var
    abc
    # 引用变量'vartest'
    $ echo $vartest
    ABC
    # 引用变量'var'并在其后加上'test'字符
    $ echo ${var}test
    abctest
  2. {}表示分组。

Reference

regexp

ERegExp

Wildcard/Glob

man 7 glob

glob - globbing pathnames. glob is a shell built-in.

主要用于匹配带有通配符的文件路径。其匹配字符串的能力比正则表达式弱。

它最初是贝尔实验室 Unix 系统上的一个名叫 glob 的命令(glob 是 global 的缩写),用于展开命令行中的通配符。后来系统提供了该功能的 C 语言库函数glob(),知名的 shell 解释器就使用了该接口,shell 脚本和命令行中使用的 glob 模式匹配功能便源自于此。——见博客。

Wildcards

{}严格来讲不属于glob的范畴,其在shell表示一个分组,见:All about {Curly Braces} in Bash。

sed

awk

awk Command

格式

1
awk -F' *|:' '/LISTEN/{print $2}'

其中,-F表示分隔符;
*|:是一个正则表达式,表示以"一个或多个空格"或":"作为分隔符;
再其后的//中是另一个正则表达式,用于匹配文本;
{}中是action。

条件判断

if-else in awk
use AND and OR in an awk program

1
awk '{if ($1 > 49151 && $1 < 65536) {print $1} }'

等价于

1
awk '$1 > 49151 && $1 < 65536'

BEGIN/END

In AWK, BEGIN and END are special patterns that allow you to execute code before processing the input (BEGIN) or after processing all the input (END).

  • The BEGIN block is executed once at the beginning of the AWK program and it is typically used for initializing variables or performing setup tasks.
  • The END block is executed once after processing all input, and it is commonly used for final caclucations, summaries, or printing results.

Special symbols

  • $ 用于引用field,例如$1代表第一个field(典型来说是第一列)。
  • NF 表示number of filed,假设一共有7列,那么$NF与$7等价。

grep

Example

  1. 找出一个未使用的port
{% tabs Code %}
1
2
3
4
5
6
7
# "$$"是为了转义"$"
max_port=$(shell netstat -antulpen 2> /dev/null \
| awk -F' *' '/^(tcp|udp)/{print $$4}' | cut -d: -f 2 \
| egrep "\w" | sort | tail -1)
#$(warning ${max_port})
port=$(shell expr $(max_port) + 1)
#$(warning ${port})
1
2
3
4
5
6
# 从1025开始找出已经存在的端口,如果相邻端口的gap大于1,则返回“当前端口号+1”
netstat -ant | awk '{print $4}' \
| awk -F: '{if ($NF ~ /^[0-9]+$/ && $NF > 1024) {print $NF}}' \
| awk 'BEGIN {prev = 1024}
{if ($1 - prev > 1) { port = prev + 1; exit} else { prev = $1}}
END { if (port=="") {print prev + 1} else {print port}}'
1
2
3
4
5
6
7
8
9
10
11
12
#这不是正则表达式
#以0端口为参数创建一个socket,则系统会自动选择一个未使用的端口号

#one-line mode:
#python -c 'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()'
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
addr = s.getsockname()
print(addr[1])
s.close()
{% endtabs %}

减少 VSCode 磁盘占用

以下文件可以删除:

  • .vscode-server/data/User/workspaceStorage/*:几十 GB.

  • .vscode-server:参考

  • .config: 可以针对每个目录找到相应的程序,比如 Chrome,然后有针对性地删除一些文件。参考
    这里。

  • .cache: 和 .config 类似处理,参考
    这里。

    .cache/vscode-cpptools: This cache folder stores cached precompiled headers or “ipch” files that
    the IntelliSense engine uses to improve performance. You can limit the size of the cache by
    changing the setting value of C_Cpp.intelliSenseCacheSize. 参考
    这里:
    C_Cpp.intelliSenseCacheSize

快捷键

  1. 跳转到对应大括号:Ctrl Shift \

用 VSCode 调试代码

实用插件

  • Remote - SSH: Windows 连接 Linux。前置条件:Windows 本身需要安装 ssh 命令行工具。
  • Perforce for VS Code: perforce 工具。
  • intent-rainbow: 用彩色显示缩进。
  • C/C++
  • Makefile Tools
  • Verilog Format
  • All in one
  • c/c++ definition generator
  • KoroFileHeader: 参考 这里。
  • 打开大文件
    • BigView
      • 加载流畅
      • 搜索语法类似 VSCode
      • 可以像 VSCode Text Editor 一样,在右下角设置高亮语法
      • 只读
    • Maximus
      • 加载 3 s 左右
      • 搜索语法有些不一样
      • 不能设置高亮语法
      • 可编辑
    • Open Log Viewer
      • 第一次打开很慢
      • 分页
      • 美观
      • 具备统计功能
      • 只支持 .log 和 .txt,其他文件后缀名需要使用 Command Palette 手动打开

实用配置

自动填充头文件,比如 ifndef 宏

配置文件:

  • launch.json
  • tasks.json:
    ref,
    ref

使用 VSCode 合并 Perforce 代码

在 ~.cshrc 脚本中添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## Use VSCode to diff/merge the Perforce code
#
# Refer to:
# https://github.com/mjcrouch/vscode-perforce/issues/259
# https://www.perforce.com/manuals/cmdref/Content/CmdRef/p4_resolve.html
#
# Map p4 resolve arguments to vscode's merge editor arguments
#
# 'code' takes: <path1> <path2> <base> <result>
#
# perforce gives:
# 1 the base file
# 2 the source file (also known as "theirs")
# 3 the target file (also known as "yours")
# 4 the merge file.
setenv P4MERGE 'code --wait --merge $2 $3 $1 $4'
setenv P4DIFF 'code --wait --diff'
setenv P4EDITOR 'code --wait'

跳转到定义如何加速

🚀 解决方案一:切换 IntelliSense 引擎 VSCode 默认使用的是 “Default” 引擎,它功能强但对大型项目解析慢
。你可以改成更轻量的 Tag Parser:

操作步骤:打开 VSCode 设置(Ctrl + ,)

搜索 C_Cpp.intelliSenseEngine

将值从 “Default” 改为 “Tag Parser”

这样跳转速度会明显提升,尤其在大型项目中。

⚙️ 解决方案二:优化智能提示延迟在设置中调整提示延迟也能改善体验:

搜索 Editor: Quick Suggestions Delay,设为 10ms 以下

搜索 Snippets Prevent Quick Suggestions,设为 false

这些设置可以让提示和跳转更流畅。

🧠 额外建议关闭未使用的扩展:某些扩展会拖慢性能

使用 compile_commands.json:如果你用 CMake,可以生成这个文件,让 VSCode 更准确地解析项目结构

避免打开整个大型项目目录:只打开你正在编辑的子目录,有助于减少分析负担

compile_commands.json

🔧 Clang 生态工具(最主要用户)

这些工具依赖 compile_commands.json 来正确解析代码:

  • Clangd:语言服务器,提供 VSCode、Vim、Emacs 等编辑器的智能补全、跳转、诊断等功能。
    • clangd 比 Microsoft 的 C/C++ 插件跳转更快,它可以手动安装到系统,也可以直接用 VSCode 的
      Extensions 市场安装(Remote SSH 也支持)。
    • compile_commands.json 是 clangd 的眼睛,把这个文件放在项目根目录或在 clangd 中手动配置其路径,可
      以显著提高跳转速度。
    • clangd 补充配置:
      • 在项目根目录创建 .clangd 文件;
      • 创建 ~/.config/clangd/config.yaml 。
    • clangd 安装方式
      • 如果系统没有 clangd server,vscode-server 在安装 clangd 插件的时候也会提示安装;如果点击安装,
        则会安装在 vscode-server 默认文件夹。
      • 如果 VSCode 没有提示安装 clangd ,那么
        • 打开命令面板(Cmd+Shift+P 或 Ctrl+Shift+P)
        • 输入并执行:Restart Language Server
        • 此时,左下角会提示 “clangd server 未安装,是否安装”
  • Clang-Tidy:静态分析工具,用于检查代码质量、风格、潜在错误
  • Include-What-You-Use (IWYU):分析并清理多余的 #include 指令
  • Clang-Format:在复杂项目中更好地格式化代码

🖥️ 智能 IDE 和编辑器 VSCode:

通过 C/C++ 插件读取 compile_commands.json 来加速跳转和补全

  • CLion、QtCreator:这些 IDE 会自动识别并使用该文件来构建项目模型

🛠️ 构建工具和生成方式 CMake:

最常见的生成方式,只需添加参数:

1
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..

就会在构建目录中生成该文件

Bear 工具:适用于非 CMake 项目(如 Makefile),通过拦截编译命令生成该文件

标签页高亮

Setting -> 搜索 “workbench.colorCustomizations” --> “Edit in setting.json”

写入以下内容:

1
2
3
4
5
"workbench.colorCustomizations": {
"tab.activeBorderTop": "#6a6ce4",
"tab.activeBackground": "#200b6c",
"tab.activeBorder": "#6a6ce4",
},

函数

glic Functions

backtrace
backtrace_symbols
backtrace_symbols_fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void print_trace() {
static const int SIZE = 10;

void* buffer[SIZE];
char** strings;
int size, i;

size = backtrace(buffer, SIZE);
strings = backtrace_symbols(buffer, size);
if (strings != NULL) {
printf("Obtained %d stack frames.\n", size);
for (i = 0; i < size; ++i)
printf("%s\n", strings[i]);
free(strings);
}
}

第三方库

breakpad: https://blog.csdn.net/weixin_45609638/article/details/125090204

https://juejin.cn/post/6899070041074073614

https://juejin.cn/post/7130820896213712927

内核编译

obj-m: 链接

make modules: 链接

编译内核模块

文档

Makefile:

obj-m += hello-1.o

all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

make -C changes to a new directory where the new makefiles will be run.

M=$(PWD) defines a variable M which the child makefiles can use.

命令

  • insmod: 插入一个模块(.ko)到kernel中。
  • rmmod: 从内核中删除一个模块。
  • modprobe: 从内核中增删模块。modprobe从/lib/modules/`uname -r`中搜索所有的模块和其他文件,除了/etc/modprobe.d目录中的可选配置文件(参见modprobe.d(5))。
  • lsmod: 显示当前加载的内核模块的状态(即对/proc/modules内容的格式化)。
  • modinfo: 从命令行指定的内核模块中提取信息,如果没有给出模块名称,那么会搜索/lib/modules/version目录,就像modprobe加载模块时一样。
  • depmod: 生成modules.dep和映射文件。
  • dmesg: 打印或控制内核ring buffer(存储kernel message)。