This commit is contained in:
2025-07-23 15:50:53 +08:00
parent 1361b15f79
commit 62013fbab9
2 changed files with 35 additions and 23 deletions

56
cap.c
View File

@@ -9,7 +9,7 @@ pcap_if_t *alldevs, *device;
pcap_t *handle; // 会话句柄
struct bpf_program fp; // 编译后的过滤器
pid_t pid = -1; // 子进程全局PID
pid_t pids[MAX_CHILDREN] = {-1}; // 子进程全局PID
#define SHM_SIZE 1024 // 共享内存大小
#define SHM_KEY 0124 // 共享内存键值
int shmid = -1;
@@ -17,7 +17,6 @@ int RULE_NAME_NUMBER = 0; // ipset 集合集合数
char *RULE_NAME = NULL; // 共享内存
char *ip2region_area = NULL; // ip2region 解析结果
char *command_result = NULL; // 执行命令的结果
void Processing_IP_addresses(char *src_ip)
{
@@ -45,19 +44,6 @@ void Processing_IP_addresses(char *src_ip)
if (1 == is_ip_in_set(cn_ip, src_ip)) {
_printf(RED "IP:%s 已经标记为国内,跳过!\n" REDEND, src_ip);
for (int i = 0; i < MAXIPSET_; i++) {
if (cn_ip[i][0] != '\0') {
printf("%s ", cn_ip[i]);
}
}
if (cn_ip_len(cn_ip) >= 10240) { // 清理集合
clear_ip_set(cn_ip);
truncate_file("cn.txt"); // 清空文件
}
printf("cn_ip_len(cn_ip): %d\n", cn_ip_len(cn_ip));
return;
}
@@ -181,8 +167,14 @@ void cleanup_(int signum)
_printf("Received signal %d, cleaning up...\n", signum);
// 终止子进程
if (pid > 0) {
kill(pid, SIGTERM);
for (int i = 0; i < MAX_CHILDREN; i++) {
if (pids[i] > 0) {
printf("Terminating child process %d...\n", pids[i]);
kill(pids[i], SIGTERM); // 优雅终止
sleep(1); // 等待其响应
kill(pids[i], SIGKILL); // 若仍未结束,强制终止
waitpid(pids[i], NULL, 0); // 回收资源
}
}
// 释放共享内存
@@ -198,10 +190,7 @@ void cleanup_(int signum)
free(ip2region_area);
ip2region_area = NULL;
}
if (command_result != NULL) {
free(command_result);
command_result = NULL;
}
// 清理
pcap_freecode(&fp);
@@ -336,8 +325,29 @@ int main(int argc, char **argv)
free(local_addr);
}
pid = fork(); // 创建子进程
if (pid == 0) // 子进程
pids[0] = fork();
if ( 0 == pids[0] ) // 子进程
{
while(1) {
for (int i = 0; i < MAXIPSET_; i++) {
if (cn_ip[i][0] != '\0') {
printf("%s ", cn_ip[i]);
}
}
printf("cn_ip_len(cn_ip): %d\n", cn_ip_len(cn_ip));
if (cn_ip_len(cn_ip) >= 10240) { // 清理集合
clear_ip_set(cn_ip);
truncate_file("cn.txt"); // 清空文件
}
sleep(60); // 每 60 秒检查一次
}
}
pids[1] = fork();
if ( 0 == pids[1] ) // 子进程
{
int count = 0;
snprintf(RULE_NAME, BUFFER, "root%d", RULE_NAME_NUMBER);

2
cap.h
View File

@@ -26,6 +26,8 @@
#define MAXIPSET 65535
#define MAXIPSET_RULT_NAME_NUM 32
#define MAX_CHILDREN 2
#define _VERSION "0.2"
#endif