From d6c6e13796435f9e1e59fec891aa53680748a2d7 Mon Sep 17 00:00:00 2001 From: We-unite <3205135446@qq.com> Date: Tue, 30 Jul 2024 19:37:48 +0800 Subject: Try to use kernel connector --- connector/test.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 connector/test.c (limited to 'connector/test.c') diff --git a/connector/test.c b/connector/test.c new file mode 100644 index 0000000..c12ad10 --- /dev/null +++ b/connector/test.c @@ -0,0 +1,64 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#define STACK_SIZE (1024 * 1024) // 定义栈大小 + +// 子任务的入口函数 +void *child_func(void *arg) +{ + printf("子任务: PID=%ld, PPID=%ld, TID=%ld\n", (long)getpid(), + (long)getppid(), (long)syscall(SYS_gettid)); + sleep(3); +} + +int main() +{ + char *stack; // 栈的指针 + char *stack_top; // 栈顶的指针 + pid_t child_tid; + pid_t forkPid; + pid_t threadPid; + + printf("主任务:我是%d\n", getpid()); + if ((forkPid = fork()) == 0) + { + sleep(3); + exit(0); + } + printf("主任务:fork子任务 %d\n", forkPid); + + pthread_create(&threadPid, NULL, child_func, NULL); + printf("主任务:create新线程%d\n", threadPid); + + // 使用 clone 创建子任务 + child_tid = clone(child_func, stack_top, SIGCHLD, NULL); + if (child_tid == -1) + { + perror("clone"); + free(stack); + exit(EXIT_FAILURE); + } + + printf("主任务: 创建了子任务, TID=%ld\n", (long)child_tid); + + // 等待子任务结束 + if (waitpid(child_tid, NULL, 0) == -1) + { + perror("waitpid"); + free(stack); + exit(EXIT_FAILURE); + } + + // 释放分配的栈 + // free(stack); + + printf("主任务: 子任务结束\n"); + return 0; +} -- cgit v1.2.3-70-g09d2