c/unix:中止运行时间过长的进程
我需要终止这样的用户进程,这些进程在 UNIX (Solaris) 操作系统上花费的时间比预期的时间间隔更长。这需要在当前正在执行的进程内完成。
请建议如何在 C 或 UNIX 中实现这一点?
I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed.
Please suggest how this can be achieved in C or in UNIX?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅
alarm()
系统调用。它为您提供了一个SIGALRM
信号,您的进程可以处理该信号并用于退出。See the
alarm()
system call. It provides you with aSIGALRM
signal which your process can handle, and use to quit.只要超时时在没有警告的情况下终止进程是可以接受的,一种替代方法是在启动进程时使用
ulimit -t
。As long as killing without warning the process in overtime is acceptable, one alternative is to use
ulimit -t <time>
at the time of launching the process.使用
setrlimit
,您可以限制进程使用的CPU时间量。一旦超出限制,您的进程将收到SIGXCPU
。With
setrlimit
, you can limit the amount of CPU time used by the process. Your process will receive aSIGXCPU
once the limit is exceeded.有一次我必须解决这个完全相同的问题。
我的解决方案如下:
编写一个控制器程序,执行以下操作:
At one time I had to solve this exact same problem.
My solution was as follows:
Write a controller program that does the following:
有一个更简单的方法。启动工作线程来完成工作,然后调用 workerThread.join(timeoutInMS) 在主线程中。那会等那么久。如果该语句返回并且工作线程仍在运行,那么您可以终止它并退出。
There's an easier way. Launch a worker thread to do the work, then call workerThread.join(timeoutInMS) in the main thread. That will wait for that long. If that statement returns and the worker thread is still running, then you can kill it and exit.