我正在尝试打印提供给线程函数“monitor_loglevel_change_handler”的参数值作为 pthread_create() 中的最后一个参数 但它打印垃圾而不是正确的值。但是,在代码的前面已提供并正确打印,请参阅注释
****(按照其他人的要求,用最小的可重现示例进一步更新了我的代码。注意,我有意将睡眠放在主程序中,以便线程函数有机会运行)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/inotify.h>
#include <errno.h>
#include <sys/stat.h>
char *read_env_param(const char*envkey)
{
if(envkey)
{
char *value = getenv(envkey);
if(value)
return strdup(value);
}
return NULL;
}
static void * monitor_loglevel_change_handler(void* arg)
{
char *fileName = (char*) arg;
int ifd; // the inotify file des
int wfd; // the watched file des
ssize_t n = 0;
char* dname=NULL; // directory name
char* bname = NULL; // basename
char* tok=NULL;
printf("Value of arguments: %s\n", (char*) arg); // --------> prints nothing why??
dname = strdup( fileName); // defrock the file name into dir and basename
if( (tok = strrchr( dname, '/' )) != NULL ) {
*tok = '\0';
bname = strdup( tok+1 );
}
ifd = inotify_init1( 0 ); // initialise watcher setting blocking read (no option)
if( ifd < 0 ) {
fprintf( stderr, "### ERR ### unable to initialise file watch %s\n", strerror( errno ) );
} else {
wfd = inotify_add_watch( ifd, dname, IN_MOVED_TO | IN_CLOSE_WRITE ); // we only care about close write changes
}
}
static int register_log_change_notify(const char *fileName)
{
pthread_attr_t cb_attr;
pthread_t tid;
pthread_attr_init(&cb_attr);
pthread_attr_setdetachstate(&cb_attr,PTHREAD_CREATE_DETACHED);
printf("file name is %s\n", fileName);
return pthread_create(&tid, &cb_attr,&monitor_loglevel_change_handler,(void *)fileName);
}
int enable_log_change_notify(const char* fileName)
{
int ret = -1;
struct stat fileInfo;
printf("filename is %s\n", fileName); // ----> prints properly
if ( lstat(fileName,&fileInfo) == 0 )
{
ret = register_log_change_notify(fileName);
}
return ret;
}
void dynamic_log_level_change()
{
char *logFile_Name = read_env_param("TESTSHA");
char* log_level_init=NULL;
if(logFile_Name)
{
printf("logFile_Name is :%s\n", logFile_Name);
free(log_level_init);
}
enable_log_change_notify(logFile_Name);
free(logFile_Name);
}
void init_log() {
int log_change_monitor = 0;
dynamic_log_level_change();
}
int main()
{
init_log();
sleep(50);
}
上面的完整代码在这里sctpThread.cpp
free(logFile_Name);
您正在释放内存,它不再有效。