diff options
Diffstat (limited to 'connector/test.c')
-rw-r--r-- | connector/test.c | 64 |
1 files changed, 64 insertions, 0 deletions
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 @@ | |||
1 | #define _GNU_SOURCE | ||
2 | #include <sched.h> | ||
3 | #include <stdio.h> | ||
4 | #include <stdlib.h> | ||
5 | #include <sys/types.h> | ||
6 | #include <sys/wait.h> | ||
7 | #include <sys/syscall.h> | ||
8 | #include <unistd.h> | ||
9 | #include <pthread.h> | ||
10 | |||
11 | #define STACK_SIZE (1024 * 1024) // 定义栈大小 | ||
12 | |||
13 | // 子任务的入口函数 | ||
14 | void *child_func(void *arg) | ||
15 | { | ||
16 | printf("子任务: PID=%ld, PPID=%ld, TID=%ld\n", (long)getpid(), | ||
17 | (long)getppid(), (long)syscall(SYS_gettid)); | ||
18 | sleep(3); | ||
19 | } | ||
20 | |||
21 | int main() | ||
22 | { | ||
23 | char *stack; // 栈的指针 | ||
24 | char *stack_top; // 栈顶的指针 | ||
25 | pid_t child_tid; | ||
26 | pid_t forkPid; | ||
27 | pid_t threadPid; | ||
28 | |||
29 | printf("主任务:我是%d\n", getpid()); | ||
30 | if ((forkPid = fork()) == 0) | ||
31 | { | ||
32 | sleep(3); | ||
33 | exit(0); | ||
34 | } | ||
35 | printf("主任务:fork子任务 %d\n", forkPid); | ||
36 | |||
37 | pthread_create(&threadPid, NULL, child_func, NULL); | ||
38 | printf("主任务:create新线程%d\n", threadPid); | ||
39 | |||
40 | // 使用 clone 创建子任务 | ||
41 | child_tid = clone(child_func, stack_top, SIGCHLD, NULL); | ||
42 | if (child_tid == -1) | ||
43 | { | ||
44 | perror("clone"); | ||
45 | free(stack); | ||
46 | exit(EXIT_FAILURE); | ||
47 | } | ||
48 | |||
49 | printf("主任务: 创建了子任务, TID=%ld\n", (long)child_tid); | ||
50 | |||
51 | // 等待子任务结束 | ||
52 | if (waitpid(child_tid, NULL, 0) == -1) | ||
53 | { | ||
54 | perror("waitpid"); | ||
55 | free(stack); | ||
56 | exit(EXIT_FAILURE); | ||
57 | } | ||
58 | |||
59 | // 释放分配的栈 | ||
60 | // free(stack); | ||
61 | |||
62 | printf("主任务: 子任务结束\n"); | ||
63 | return 0; | ||
64 | } | ||