#![no_std]
#![no_main]

#[macro_use]
extern crate user_lib;
use user_lib::{exit, fork, sched_yield, wait, waitpid};

const MAGIC: i32 = -0x10384;

// 教学目标：
// 验证 waitpid 只等待目标子进程，且可正确获取退出码。

#[unsafe(no_mangle)]
extern "C" fn main() -> i32 {
    println!("I am the parent. Forking the child...");
    let pid = fork();
    if pid == 0 {
        println!("I am the child.");
        for _ in 0..7 {
            sched_yield();
        }
        exit(MAGIC);
    } else {
        println!("I am parent, fork a child pid {}", pid);
    }
    println!("I am the parent, waiting now..");
    let mut xstate: i32 = 0;
    assert!(waitpid(pid, &mut xstate) == pid && xstate == MAGIC);
    assert!(waitpid(pid, &mut xstate) < 0 && wait(&mut xstate) <= 0);
    println!("waitpid {} ok.", pid);
    println!("exit pass.");
    0
}
