aboutsummaryrefslogtreecommitdiffstats
path: root/connector/test.c
blob: c12ad10847950c2c451fb5289ef966478638c8f0 (plain) (blame)
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
56
57
58
59
60
61
62
63
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;
}