0

我想用运行时的 exec() 方法在 Java 中运行一个 C 程序。Java 代码如下:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
process.waitFor();

在这种情况下,如何定义编译后的 C 程序的运行时间?我的意思是,如果我可以设置一个时间间隔,并且如果代码没有在该间隔内完成运行,那么返回一个超出时间限制的错误?

4

3 回答 3

2

我认为您应该在这里更好地考虑多线程编程。一旦您开始在 JVM 之外执行程序,您就无法真正从 Java 中分辨出“停止执行该程序”......

因此,您可能应该在单独的线程中运行您在此处提供的代码并使用

Object.wait(long milliseconds)

等待这个线程的结果。如果您没有得到结果,请继续您的程序。

于 2012-07-03T07:21:33.047 回答
0

Took me some time to understand what you would like to achieve, but here goes my suggestion -
A. Have your code snippet executed in another thread , let's say the Runnable implementation will look like:
public class ProcessExecutor implements Runnable {

private String command;

public ProcessExecutor(String command) { this.command = command; }

public void run() { Runtime runtime = RUntime.getRuntime(); Process process = runtime.exec(command); ProcessManager.getInstance().add(process); process.waitFor(); } }

ProcessManager is a synchronized singletone collection for tracking process execution that you will develop.
It can be a map, based on process ID, that will hold as value the process itself, and information on start time and the last check time.
You should use the ScheduledExecutorService to run a scheduled task that will periodically check that status of the executed processes. For each process it can manage the last check time, and if lastCheckTime - startTime exceeds a certain interval it should state there is an error, and maybe destroy the process using the destroy method/

于 2012-07-03T07:27:42.290 回答
0

您可以(在Linux或 Posix 系统上)commandulimit -t 120; yourprogram and arguments.

这只会限制 CPU 时间;如果yourprogram在某些输入上无限休眠或阻塞,则无济于事。

马克的回答建议多线程方法可能更好。但我的确实限制了资源。

于 2012-07-03T07:22:52.260 回答