我在我的 BeagleBone Black 上使用 localtime 为事件添加时间戳。我正在运行一个多线程应用程序并意识到 localtime 不是线程安全的。所以我切换到 localtime_r,这会生成一个段错误。请找到附件中的图片。
- 我在我的桌面上执行了相同的程序,该程序是 x86_64 系统,具有不同的 linux 内核版本并且它可以工作。用另一个具有更新内核的 64 位系统再次尝试它,但它不起作用。
- 没有在网上找到很多关于这个问题的文献。 This有一些信息但不清楚。
关于如何解决这个问题有什么建议吗?不确定为什么它适用于某些系统而不适用于其他系统。
更新 1:我已经发布了代码
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
int main(){
int day, month, hour, minute, second, year;
time_t t = time(NULL);
struct tm *result;
struct tm *tm = localtime_r(&t, result);
day = result->tm_mday;
month = (result->tm_mon+1);
hour = result->tm_hour;
minute = result->tm_min;
second = result->tm_sec;
year = (result->tm_year-100);
printf("%d : %d : %d : %d:%d:%d\n", month, day, year, hour, minute, second);
return 0;
}
最佳答案
struct tm *result;
struct tm *tm = localtime_r(&t, result);
您将垃圾传递给 localtime_r
。您没有将 result
初始化为任何特定的值,而是将其值传递给 localtime_r
。
也许你想要:
time_t t = time(NULL);
struct tm result;
struct tm *tm = localtime_r(&t, &result);
关于c - 如何解决localtime_r时区段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37935134/