C Linux中处理系统(命令)调用超时
我正在尝试使用linux系统(cmd)执行一个命令(从远程服务器获取密钥)。我的问题是,当远程服务器无法访问时,对于少数IP,它只是等待而不返回,这反过来会使“system()”永远挂起。我想处理这种情况。我正在考虑一种方法,使我的system()等待一定的时间,如果命令没有返回,那么system()命令必须出来报告一个不成功的状态 我的命令如下所示:C Linux中处理系统(命令)调用超时,c,linux,shell,signals,fork,C,Linux,Shell,Signals,Fork,我正在尝试使用linux系统(cmd)执行一个命令(从远程服务器获取密钥)。我的问题是,当远程服务器无法访问时,对于少数IP,它只是等待而不返回,这反过来会使“system()”永远挂起。我想处理这种情况。我正在考虑一种方法,使我的system()等待一定的时间,如果命令没有返回,那么system()命令必须出来报告一个不成功的状态 我的命令如下所示: int status = system("<<<URL of the remote server>>>");
int status = system("<<<URL of the remote server>>>");
//the above command must wait for a fixed duration before coming out if no response.
int status=system(“”);
//如果没有响应,上述命令必须等待一段固定的时间才能发出。
您可以使用该命令来执行此操作
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
}
但是,正如评论中所提到的,您最好使用面向网络的解决方案来解决您的情况中潜在的问题,例如。您可以使用该命令来完成此操作
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
}
然而,正如评论中所提到的,你最好用一个面向网络的解决方案来解决你的处境中的潜在问题,例如。当然有一个unix程序可以做到这一点……当然有一个unix程序可以做到这一点……您可以使用cURL而不是使用system从服务器获取数据,因为它提供了设置超时的选项。您可以使用cURL而不是使用system从服务器获取数据,因为它提供了设置超时的选项