#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; }