c/unix:中止运行时间过长的进程

发布于 2024-09-17 11:54:46 字数 111 浏览 6 评论 0原文

我需要终止这样的用户进程,这些进程在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

旧伤还要旧人安 2024-09-24 11:54:46

请参阅 alarm() 系统调用。它为您提供了一个 SIGALRM 信号,您的进程可以处理该信号并用于退出。

See the alarm() system call. It provides you with a SIGALRM signal which your process can handle, and use to quit.

峩卟喜欢 2024-09-24 11:54:46

只要超时时在没有警告的情况下终止进程是可以接受的,一种替代方法是在启动进程时使用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.

阳光下的泡沫是彩色的 2024-09-24 11:54:46

使用setrlimit,您可以限制进程使用的CPU时间量。一旦超出限制,您的进程将收到 SIGXCPU

#include <sys/resource.h>
struct rlimit limits = {42, RLIM_INFINITY};
setrlimit(RLIMIT_CPU, &limits);

With setrlimit, you can limit the amount of CPU time used by the process. Your process will receive a SIGXCPU once the limit is exceeded.

#include <sys/resource.h>
struct rlimit limits = {42, RLIM_INFINITY};
setrlimit(RLIMIT_CPU, &limits);
南街女流氓 2024-09-24 11:54:46

有一次我必须解决这个完全相同的问题。

我的解决方案如下:

编写一个控制器程序,执行以下操作:

  1. 分叉一个子进程来启动您想要控制的进程。
  2. 返回父进程,派生第二个子进程,该子进程会休眠允许的最长时间,然后退出。
  3. 在父级中,等待子级完成,无论哪个先完成都会导致父级杀死另一个。

At one time I had to solve this exact same problem.

My solution was as follows:

Write a controller program that does the following:

  1. Fork a child process that starts the process you want to control.
  2. Back in the parent, fork a second child process that sleeps for the maximum time allowed and then exits.
  3. In the parent, wait for the children to complete and whichever finishes first causes the parent to kill the other.
流星番茄 2024-09-24 11:54:46

有一个更简单的方法。启动工作线程来完成工作,然后调用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文