调用 shell 脚本,尤其是频繁调用,会削弱程序的性能,因此请改用内置的日志记录功能。您可能需要更改语义,logData()
因为我不知道您的“命令”和“地址”采用什么形式。
记录器.h:
#pragma once
#include <stdbool.h>
extern bool logOpen(const char *filename);
extern void logData(const char *command, const char *address);
extern void logClose();
记录器.c:
#include "logger.h"
#include <stdio.h>
#include <sys/time.h>
static FILE *logfp = NULL;
bool logOpen(const char *filename) {
logfp = fopen(filename, "w+");
return logfp != NULL;
}
void logData(const char *command, const char *address) {
struct timeval tv;
struct tm tm;
if (!logfp)
return;
gettimeofday(&tv, 0);
localtime_r(&tv.tv_sec, &tm);
fprintf(logfp, "%02d:%02d:%02d.%03u: command='%s' address='%s'\n",
tm.tm_hour, tm.tm_min, tm.tm_sec, (unsigned)(tv.tv_usec / 1000),
command, address);
}
void logClose() {
if (logfp) {
fclose(logfp);
logfp = NULL;
}
}
主.c:
#include "logger.h"
int main(int argc, const char **argv) {
logOpen("file.log");
logData("Command 1", "Address 1");
logData("Command 2", "Address 2");
logData("Command 3", "Address 3");
logData("Command 4", "Address 4");
logClose();
return 0;
}
编译和测试:
$ clang -o test main.c logger.c
$ ./test
$ more file.log
13:40:08.399: command='Command 1' address='Address 1'
13:40:08.399: command='Command 2' address='Address 2'
13:40:08.399: command='Command 3' address='Address 3'
13:40:08.399: command='Command 4' address='Address 4'