如何在循环迭代结束时获取当前时间,区分远程服务器日志中的循环迭代
如何在循环迭代结束时获取当前时间,区分远程服务器日志中的循环迭代
嗨,我看了你的代码,问题其实挺明显的——你把time_t t = time(NULL);放在了循环外面,这就导致t只在程序启动时获取了一次时间,后面每次循环用的都是这个初始时间,自然日志里的时间全是一样的啦。
要解决这个问题,你只需要把获取当前时间的代码移到循环内部,让每次迭代都重新抓取最新的系统时间就行。具体来说,把获取时间戳和转换本地时间的代码都放到循环里,每次执行到日志打印步骤时,都会拿到当前的实时时间。
这里是修改后的完整代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <libssh/libssh.h> #define BILLION 1000000000.0 int main(void) { struct timespec start, finish; ssh_session session; int rc; int session_status; session = ssh_new(); const char *host = "127.0.0.1"; const char *port = "22"; const char *username = "user"; const char *password = "pass"; char *reply; ssh_options_set(session, SSH_OPTIONS_HOST, host); ssh_options_set(session, SSH_OPTIONS_PORT_STR, port); ssh_options_set(session, SSH_OPTIONS_USER, username); session_status = ssh_get_status(session); printf("Session status: %d\n", session_status); for (int i = 0; i < 4; ++i) { clock_gettime(CLOCK_REALTIME, &start); rc = ssh_connect(session); if (rc != SSH_OK) { fprintf(stderr, "Error connecting to %s: %s\n", host, ssh_get_error(session)); ssh_free(session); exit(-1); } if (ssh_userauth_password(session, NULL, password) == SSH_AUTH_SUCCESS) { reply = "Authentication succeeded with incorrect password."; } else { reply = "Authentication failed with incorrect password."; } clock_gettime(CLOCK_REALTIME, &finish); double time_spent = (finish.tv_sec - start.tv_sec) + (finish.tv_nsec - start.tv_nsec) / BILLION; // 核心修改:把获取当前时间的逻辑移到循环内部,每次迭代更新时间 time_t t = time(NULL); struct tm tm = *localtime(&t); printf("[%d-%02d-%02d %02d:%02d:%02d] Status:%s ", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, reply); printf("Elapsed time: %.4f seconds.\n", time_spent); ssh_disconnect(session); } ssh_free(session); return (0); }
额外提一句,如果你的程序是多线程环境,可以改用线程安全的localtime_r()替代localtime(),用法很类似:
struct tm tm; localtime_r(&t, &tm);
单线程程序的话,用localtime()完全没问题。
备注:内容来源于stack exchange,提问作者AbreQueVoy
相关产品推荐
相关产品推荐

