enum stats {OK,TLE,RE};
struct runstats{
stats stat;
int exitcode;
};
runstats system_tle(const char* tor,int tle){
runstats result;
auto Start=std::chrono::steady_clock::now();
pid_t p1=fork();
if (p1==0){
int ec=std::system(tor);
if (ec) result.stat=RE; else result.stat=OK;
result.exitcode=ec;
}else{
bool done=false;
while (std::chrono::steady_clock::now()<Start+std::chrono::milliseconds(tle*1000)&&!done)
if (kill(p1,0)!=0) done=true;
if (!done){
kill(p1,SIGKILL);
result.stat=TLE;
result.exitcode=-1;
}else exit(0);
}
return result;
}
我想用这段代码实现system函数的定时,也就是system在指定时间内不退出,用另外一个进程kill之。但以上这段代码为什么会出现问题?问题大概是这样的,无论子进程是否在规定时间内跑完,主线程都会执行一次kill并返回错误的结果。
巴扎黑2017-04-17 13:41:43
Since your purpose description is not very clear, I can only guess that your intention is: the system (tor) call may be blocked forever or for a long time. If it has not been executed within the specified time, kill it. ?
I won’t answer this question until I get your confirmation. After reading your code, I have two serious problems.
First, the parent and child processes have their own data memory space. Linux uses copy on write technology. After fork, the child process will share data with the parent process, but once the child process modifies the data, a copy will be copied out. Just like the result in the code, the child process has one copy and the parent process has one copy, each of which has nothing to do with it. The way you write your code is to treat multiple processes as multiple threads!
Second, kill the main process pid and send a signal to the main process. Usually the main process is the leader of the process group in a multi-process. The group leader and all child processes in the group will receive the signal, including the program executed by the system function. It also belongs to a child process, unless the process executed by the system changes the process group ID. Once this SIGKILL is issued, it means that all processes, including child processes, will be forcibly killed. In this case, no logical judgment and processing can be performed inside the program. The entire program will exit abnormally?