| 11 | #include "task_messages.hpp" |
| 12 | |
| 13 | auto TaskManager::Wait(Pid pid, int* status, bool no_hang, bool untraced) |
| 14 | -> Expected<Pid> { |
| 15 | auto* current = GetCurrentTask(); |
| 16 | assert(current != nullptr && "Wait: No current task"); |
| 17 | assert(current->GetStatus() == TaskStatus::kRunning && |
| 18 | "Wait: current task status must be kRunning"); |
| 19 | |
| 20 | while (true) { |
| 21 | TaskControlBlock* target = nullptr; |
| 22 | bool did_block = false; |
| 23 | bool has_matching_child = false; |
| 24 | |
| 25 | { |
| 26 | // 锁顺序: cpu_sched.lock → task_table_lock_(与 Exit 一致) |
| 27 | auto& cpu_sched = GetCurrentCpuSched(); |
| 28 | LockGuard<SpinLock> sched_guard(cpu_sched.lock); |
| 29 | LockGuard<SpinLock> table_guard(task_table_lock_); |
| 30 | |
| 31 | for (auto& [task_pid, task] : task_table_) { |
| 32 | bool is_child = (task->aux->parent_pid == current->pid); |
| 33 | |
| 34 | bool pid_match = false; |
| 35 | if (pid == static_cast<Pid>(-1)) { |
| 36 | pid_match = is_child; |
| 37 | } else if (pid == 0) { |
| 38 | pid_match = is_child && (task->aux->pgid == current->aux->pgid); |
| 39 | } else if (pid > 0) { |
| 40 | pid_match = is_child && (task->pid == pid); |
| 41 | } else { |
| 42 | pid_match = is_child && (task->aux->pgid == static_cast<Pid>(-pid)); |
| 43 | } |
| 44 | |
| 45 | if (!pid_match) { |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | has_matching_child = true; |
| 50 | |
| 51 | if (task->GetStatus() == TaskStatus::kZombie || |
| 52 | task->GetStatus() == TaskStatus::kExited) { |
| 53 | target = task.get(); |
| 54 | break; |
| 55 | } |
| 56 | |
| 57 | if (untraced && task->GetStatus() == TaskStatus::kBlocked) { |
| 58 | if (status) { |
| 59 | *status = 0; |
| 60 | } |
| 61 | return task->pid; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // 没有匹配的子进程,返回错误(类似 POSIX ECHILD) |
| 66 | if (!has_matching_child) { |
| 67 | return std::unexpected(Error{ErrorCode::kTaskNoChildFound}); |
| 68 | } |
| 69 | |
| 70 | // 原子性:在持有两把锁的情况下检查并阻塞,防止丢失唤醒 |