/*1212
 * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "it_pthread_test.h"

static volatile int g_count = 0;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_testAtforkCount = 0;
static int g_testAtforkPrepare = 0;
static int g_testAtforkParent = 0;
static int g_testAtforkChild = 0;
static const int SLEEP_TIME = 2;

static void Prepare()
{
    int err;
    ICUNIT_ASSERT_EQUAL_VOID(g_testAtforkCount, 1, g_testAtforkCount);
//    这是一个宏，用于检查条件是否满足。如果条件不满足，测试会停止并输出相应的信息。这里的作用是确保 g_testAtforkCount 等于 1。
    err = pthread_mutex_lock(&g_lock);
//    这行代码试图获取互斥锁 g_lock，如果获取成功，g_testAtforkPrepare 会自增，表示该线程执行了准备工作。
    ICUNIT_ASSERT_EQUAL_VOID(err, 0, err);
    g_testAtforkPrepare++;
}

static void Parent()
{
    int err;
    ICUNIT_ASSERT_EQUAL_VOID(g_testAtforkCount, 1, g_testAtforkCount);

    err = pthread_mutex_unlock(&g_lock);
//    这行代码释放之前在 Prepare 函数中锁定的互斥量 g_lock，允许其他线程访问临界区。
    ICUNIT_ASSERT_EQUAL_VOID(err, 0, err);
    g_testAtforkParent++;
//    增加 g_testAtforkParent，表示父进程执行完其相关操作。
}

static void child()
{
    int err;
    ICUNIT_ASSERT_EQUAL_VOID(g_testAtforkCount, 1, g_testAtforkCount);

    err = pthread_mutex_unlock(&g_lock);
    ICUNIT_ASSERT_EQUAL_VOID(err, 0, err);
    g_testAtforkChild++;
//    增加 g_testAtforkChild，表示子进程执行完其相关操作。
}

static void *ThreadProc(void *arg)
{
    int err;
    
    // 进入一个循环，直到 g_count 达到 5。
    while (g_count < 5) { 
        // 锁住互斥量 g_lock，保护 g_count 的更新，防止并发修改。
        err = pthread_mutex_lock(&g_lock);
        ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

        // 增加 g_count 的值，表示执行了一次计数。
        g_count++;

        // 调用 SLEEP_AND_YIELD 宏函数，让当前线程休眠一段时间并让出 CPU，允许其他线程执行。
        SLEEP_AND_YIELD(SLEEP_TIME);

        // 解锁互斥量 g_lock，允许其他线程访问被保护的资源。
        err = pthread_mutex_unlock(&g_lock);
        ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

        // 再次调用 SLEEP_AND_YIELD 宏函数，让当前线程休眠并让出 CPU。
        SLEEP_AND_YIELD(SLEEP_TIME);
    }

EXIT:
    return NULL;
}


static void *PthreadAtforkTest(void *arg)
{
    int err;
    pid_t pid;
    pthread_t tid;
    int status = 0;

    // 初始化共享变量 g_count 和测试相关的变量
    g_count = 0;
    g_testAtforkCount = 0;
    g_testAtforkPrepare = 0;
    g_testAtforkParent = 0;
    g_testAtforkChild = 0;

    // 创建一个新的线程
    err = pthread_create(&tid, NULL, ThreadProc, NULL);
    ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

    // 注册 fork 前的处理函数
    err = pthread_atfork(Prepare, Parent, child);
    ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

    // 更新测试计数器，标记已创建线程
    g_testAtforkCount++;

    // 休眠并让出 CPU 控制
    SLEEP_AND_YIELD(SLEEP_TIME);

    // 调用 fork() 创建子进程
    pid = fork();
    ICUNIT_GOTO_WITHIN_EQUAL(pid, 0, 100000, pid, EXIT); // 100000, PID 不会超过 100000
    ICUNIT_GOTO_EQUAL(g_testAtforkPrepare, 1, g_testAtforkPrepare, EXIT);

    // 子进程的处理逻辑
    if (pid == 0) {
        // 子进程中，检查 g_testAtforkChild 是否为 1，确认子进程的状态
        ICUNIT_GOTO_EQUAL(g_testAtforkChild, 1, g_testAtforkChild, EXIT);

        // 子进程进入循环，直到 g_count 达到 5
        while (g_count < 5) {
            // 加锁，保护 g_count
            err = pthread_mutex_lock(&g_lock);
            ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

            // 增加 g_count
            g_count++;

            // 休眠并让出 CPU 控制
            SLEEP_AND_YIELD(SLEEP_TIME);

            // 解锁
            err = pthread_mutex_unlock(&g_lock);
            ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);

            // 休眠并让出 CPU 控制
            SLEEP_AND_YIELD(SLEEP_TIME);
        }

        // 子进程退出，设置退出状态为 15
        exit(15); // 15, 设置退出状态
    }

    // 父进程中，检查 g_testAtforkParent 是否为 1，确认父进程的状态
    ICUNIT_GOTO_EQUAL(g_testAtforkParent, 1, g_testAtforkParent, EXIT_WAIT);

    // 等待子线程结束
    err = pthread_join(tid, NULL);
    ICUNIT_GOTO_EQUAL(err, 0, err, EXIT_WAIT);
// 
    // 父进程等待子进程退出 
    err = waitpid(pid, &status, 0);
    status = WEXITSTATUS(status);  // 获取子进程的退出状态
    ICUNIT_GOTO_EQUAL(err, pid, err, EXIT);
    ICUNIT_GOTO_EQUAL(status, 15, status, EXIT); // 检查子进程的退出状态是否为 15

EXIT:
    return NULL;

EXIT_WAIT:
    // 父进程等待子进程退出
    (void)waitpid(pid, &status, 0);
    return NULL;
}


static int Testcase()
{
    int ret;
    pthread_t newPthread;
    int curThreadPri, curThreadPolicy;
    pthread_attr_t a = { 0 };
    struct sched_param param = { 0 };

    ret = pthread_getschedparam(pthread_self(), &curThreadPolicy, &param);
    ICUNIT_ASSERT_EQUAL(ret, 0, -ret);

    curThreadPri = param.sched_priority;

    ret = pthread_attr_init(&a);
    pthread_attr_setinheritsched(&a, PTHREAD_EXPLICIT_SCHED);
    param.sched_priority = curThreadPri + 2; // 2, adjust the priority.
    pthread_attr_setschedparam(&a, &param);
    ret = pthread_create(&newPthread, &a, PthreadAtforkTest, 0);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = pthread_join(newPthread, NULL);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    return 0;
}

void ItTestPthreadAtfork001(void)
{
    TEST_ADD_CASE("IT_PTHREAD_ATFORK_001", Testcase, TEST_POSIX, TEST_MEM, TEST_LEVEL0, TEST_FUNCTION);
}
