在 Linux 中处理系统(命令)调用超时

pab*_*han 0 c linux shell fork signals

我正在尝试使用 linux 的系统(cmd)执行命令(从远程服务器获取密钥)。我的问题是当远程服务器无法访问时,对于少数 IP,它只是等待而不返回,这反过来使“system()”永远挂起。我想处理这种情况。我在想一种方法让我的 system() 等待一段时间,如果命令没有返回,那么 system() 命令必须出来报告不成功的状态。

我的命令看起来像这样:

int status = system("<<<URL of the remote server>>>");
//the above command must wait for a fixed duration before coming out if no response.
Run Code Online (Sandbox Code Playgroud)

344*_*442 6

您可以使用该timeout(1)命令来执行此操作...

int status = system("timeout 60 whatever-command-you-want-to-run");
if(status != 0) {
    // Uh, oh! Either something went wrong, or the command time out after 60 seconds
}
Run Code Online (Sandbox Code Playgroud)

但是,正如评论中所述,您最好使用面向网络的解决方案来解决您的情况的潜在问题,例如requests.