pid 控制

static std::map<pid_t, TTask *> Tasks;

TError TTask::Fork(bool detach) {
PORTO_ASSERT(!PostFork);
auto lock = std::unique_lock<std::mutex>(ForkLock);
ForkTime = time(NULL);
localtime_r(&ForkTime, &ForkLocalTime);
pid_t ret = fork();
if (ret < 0)
return TError::System("TTask::Fork");
Pid = ret;
if (!Pid)
PostFork = true;
else if (!detach)
Tasks[Pid] = this;
Running = true;
return OK;
}

TError TTask::Wait() {
auto lock = std::unique_lock<std::mutex>(ForkLock);
if (Running) {
pid_t pid = Pid;
int status;
lock.unlock();
/* main thread could be blocked on lock that we're holding */
if (waitpid(pid, &status, 0) == pid)
pid = 0;
lock.lock();
if (!pid) {
if (Running) {
Tasks.erase(Pid);
Running = false;
}
Status = status;
}
}
while (Running) {
if (kill(Pid, 0) && errno == ESRCH) {
Tasks.erase(Pid);
Running = false;
Status = 100;
return TError("task not found");
}
if (Tasks.find(Pid) == Tasks.end())
return TError("detached task");
TasksCV.wait(lock);
}
if (Status)
return TError(EError::Unknown, FormatExitStatus(Status));
return OK;
}

猜你喜欢

转载自www.cnblogs.com/hshy/p/11964384.html