在 Linux 中处理系统(命令)调用超时
handling system(command) call timeout in Linux
我正在尝试使用 linux 的系统 (cmd) 执行命令(从远程服务器获取密钥)。我的问题是当远程服务器无法访问时,对于少数 IP,它只是等待而不是 return,这反过来使 "system()" 永远挂起。我想处理这种情况。我正在想办法让我的 system() 等待一段时间,如果命令没有 return,那么 system() 命令必须报告不成功状态。
我的命令看起来像这样:
int status = system("<<<URL of the remote server>>>");
//the above command must wait for a fixed duration before coming out if no response.
您可以使用 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
}
但是,如评论中所述,您最好使用面向网络的解决方案来解决您所处情况的潜在问题,例如 requests
。
我正在尝试使用 linux 的系统 (cmd) 执行命令(从远程服务器获取密钥)。我的问题是当远程服务器无法访问时,对于少数 IP,它只是等待而不是 return,这反过来使 "system()" 永远挂起。我想处理这种情况。我正在想办法让我的 system() 等待一段时间,如果命令没有 return,那么 system() 命令必须报告不成功状态。
我的命令看起来像这样:
int status = system("<<<URL of the remote server>>>");
//the above command must wait for a fixed duration before coming out if no response.
您可以使用 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
}
但是,如评论中所述,您最好使用面向网络的解决方案来解决您所处情况的潜在问题,例如 requests
。