您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ snprintfz函数代码示例

51自学网 2021-06-03 08:04:32
  C++
这篇教程C++ snprintfz函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中snprintfz函数的典型用法代码示例。如果您正苦于以下问题:C++ snprintfz函数的具体用法?C++ snprintfz怎么用?C++ snprintfz使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了snprintfz函数的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: calculated_number_fabs

static inline char *format_value_with_precision_and_unit(char *value_string, size_t value_string_len, calculated_number value, const char *units, int precision) {    if(unlikely(isnan(value) || isinf(value)))        value = 0.0;    char *separator = "";    if(unlikely(isalnum(*units)))        separator = " ";    if(precision < 0) {        int len, lstop = 0, trim_zeros = 1;        calculated_number abs = value;        if(isless(value, 0)) {            lstop = 1;            abs = calculated_number_fabs(value);        }        if(isgreaterequal(abs, 1000)) {            len = snprintfz(value_string, value_string_len, "%0.0" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);            trim_zeros = 0;        }        else if(isgreaterequal(abs, 10))     len = snprintfz(value_string, value_string_len, "%0.1" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else if(isgreaterequal(abs, 1))      len = snprintfz(value_string, value_string_len, "%0.2" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else if(isgreaterequal(abs, 0.1))    len = snprintfz(value_string, value_string_len, "%0.2" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else if(isgreaterequal(abs, 0.01))   len = snprintfz(value_string, value_string_len, "%0.4" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else if(isgreaterequal(abs, 0.001))  len = snprintfz(value_string, value_string_len, "%0.5" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else if(isgreaterequal(abs, 0.0001)) len = snprintfz(value_string, value_string_len, "%0.6" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        else                                 len = snprintfz(value_string, value_string_len, "%0.7" LONG_DOUBLE_MODIFIER, (LONG_DOUBLE) value);        if(unlikely(trim_zeros)) {            int l;            // remove trailing zeros from the decimal part            for(l = len - 1; l > lstop; l--) {                if(likely(value_string[l] == '0')) {                    value_string[l] = '/0';                    len--;                }                else if(unlikely(value_string[l] == '.')) {                    value_string[l] = '/0';                    len--;                    break;                }                else                    break;            }        }        if(unlikely(len <= 0)) len = 1;        snprintfz(&value_string[len], value_string_len - len, "%s%s", separator, units);    }    else {        if(precision > 50) precision = 50;        snprintfz(value_string, value_string_len, "%0.*" LONG_DOUBLE_MODIFIER "%s%s", precision, (LONG_DOUBLE) value, separator, units);    }    return value_string;}
开发者ID:leirenzhichui,项目名称:netdata,代码行数:59,


示例2: read_cgroup_plugin_configuration

void read_cgroup_plugin_configuration() {	cgroup_check_for_new_every = config_get_number("plugin:cgroups", "check for new cgroups every", cgroup_check_for_new_every);	cgroup_enable_cpuacct_stat = config_get_boolean_ondemand("plugin:cgroups", "enable cpuacct stat", cgroup_enable_cpuacct_stat);	cgroup_enable_cpuacct_usage = config_get_boolean_ondemand("plugin:cgroups", "enable cpuacct usage", cgroup_enable_cpuacct_usage);	cgroup_enable_memory = config_get_boolean_ondemand("plugin:cgroups", "enable memory", cgroup_enable_memory);	cgroup_enable_blkio = config_get_boolean_ondemand("plugin:cgroups", "enable blkio", cgroup_enable_blkio);	char filename[FILENAME_MAX + 1], *s;	struct mountinfo *mi, *root = mountinfo_read();	mi = mountinfo_find_by_filesystem_mount_source(root, "cgroup", "cpuacct");	if(!mi) mi = mountinfo_find_by_filesystem_super_option(root, "cgroup", "cpuacct");	if(!mi) {		error("Cannot find cgroup cpuacct mountinfo. Assuming default: /sys/fs/cgroup/cpuacct");		s = "/sys/fs/cgroup/cpuacct";	}	else s = mi->mount_point;	snprintfz(filename, FILENAME_MAX, "%s%s", global_host_prefix, s);	cgroup_cpuacct_base = config_get("plugin:cgroups", "path to /sys/fs/cgroup/cpuacct", filename);	mi = mountinfo_find_by_filesystem_mount_source(root, "cgroup", "blkio");	if(!mi) mi = mountinfo_find_by_filesystem_super_option(root, "cgroup", "blkio");	if(!mi) {		error("Cannot find cgroup blkio mountinfo. Assuming default: /sys/fs/cgroup/blkio");		s = "/sys/fs/cgroup/blkio";	}	else s = mi->mount_point;	snprintfz(filename, FILENAME_MAX, "%s%s", global_host_prefix, s);	cgroup_blkio_base = config_get("plugin:cgroups", "path to /sys/fs/cgroup/blkio", filename);	mi = mountinfo_find_by_filesystem_mount_source(root, "cgroup", "memory");	if(!mi) mi = mountinfo_find_by_filesystem_super_option(root, "cgroup", "memory");	if(!mi) {		error("Cannot find cgroup memory mountinfo. Assuming default: /sys/fs/cgroup/memory");		s = "/sys/fs/cgroup/memory";	}	else s = mi->mount_point;	snprintfz(filename, FILENAME_MAX, "%s%s", global_host_prefix, s);	cgroup_memory_base = config_get("plugin:cgroups", "path to /sys/fs/cgroup/memory", filename);	mi = mountinfo_find_by_filesystem_mount_source(root, "cgroup", "devices");	if(!mi) mi = mountinfo_find_by_filesystem_super_option(root, "cgroup", "devices");	if(!mi) {		error("Cannot find cgroup devices mountinfo. Assuming default: /sys/fs/cgroup/devices");		s = "/sys/fs/cgroup/devices";	}	else s = mi->mount_point;	snprintfz(filename, FILENAME_MAX, "%s%s", global_host_prefix, s);	cgroup_devices_base = config_get("plugin:cgroups", "path to /sys/fs/cgroup/devices", filename);	cgroup_root_max = config_get_number("plugin:cgroups", "max cgroups to allow", cgroup_root_max);	cgroup_max_depth = config_get_number("plugin:cgroups", "max cgroups depth to monitor", cgroup_max_depth);	cgroup_enable_new_cgroups_detected_at_runtime = config_get_boolean("plugin:cgroups", "enable new cgroups detected at run time", cgroup_enable_new_cgroups_detected_at_runtime);	mountinfo_free(root);}
开发者ID:TotoYY,项目名称:netdata,代码行数:58,


示例3: registry_set_cookie

static void registry_set_cookie(struct web_client *w, const char *guid) {    char edate[100];    time_t et = now_realtime_sec() + registry.persons_expiration;    struct tm etmbuf, *etm = gmtime_r(&et, &etmbuf);    strftime(edate, sizeof(edate), "%a, %d %b %Y %H:%M:%S %Z", etm);    snprintfz(w->cookie1, NETDATA_WEB_REQUEST_COOKIE_SIZE, NETDATA_REGISTRY_COOKIE_NAME "=%s; Expires=%s", guid, edate);    if(registry.registry_domain && registry.registry_domain[0])        snprintfz(w->cookie2, NETDATA_WEB_REQUEST_COOKIE_SIZE, NETDATA_REGISTRY_COOKIE_NAME "=%s; Domain=%s; Expires=%s", guid, registry.registry_domain, edate);}
开发者ID:cppmx,项目名称:netdata,代码行数:11,


示例4: config_get

char *rrdset_cache_dir(const char *id){	char *ret = NULL;	static char *cache_dir = NULL;	if(!cache_dir) {		cache_dir = config_get("global", "cache directory", CACHE_DIR);		int r = mkdir(cache_dir, 0755);		if(r != 0 && errno != EEXIST)			error("Cannot create directory '%s'", cache_dir);	}	char b[FILENAME_MAX + 1];	char n[FILENAME_MAX + 1];	rrdset_strncpyz_name(b, id, FILENAME_MAX);	snprintfz(n, FILENAME_MAX, "%s/%s", cache_dir, b);	ret = config_get(id, "cache directory", n);	if(rrd_memory_mode == RRD_MEMORY_MODE_MAP || rrd_memory_mode == RRD_MEMORY_MODE_SAVE) {		int r = mkdir(ret, 0775);		if(r != 0 && errno != EEXIST)			error("Cannot create directory '%s'", ret);	}	return ret;}
开发者ID:4224657,项目名称:netdata,代码行数:27,


示例5: do_proc_sys_kernel_random_entropy_avail

int do_proc_sys_kernel_random_entropy_avail(int update_every, usec_t dt) {    (void)dt;    static procfile *ff = NULL;    if(unlikely(!ff)) {        char filename[FILENAME_MAX + 1];        snprintfz(filename, FILENAME_MAX, "%s%s", netdata_configured_host_prefix, "/proc/sys/kernel/random/entropy_avail");        ff = procfile_open(config_get("plugin:proc:/proc/sys/kernel/random/entropy_avail", "filename to monitor", filename), "", PROCFILE_FLAG_DEFAULT);        if(unlikely(!ff)) return 1;    }    ff = procfile_readall(ff);    if(unlikely(!ff)) return 0; // we return 0, so that we will retry to open it next time    unsigned long long entropy = str2ull(procfile_lineword(ff, 0, 0));    RRDSET *st = rrdset_find_bytype("system", "entropy");    if(unlikely(!st)) {        st = rrdset_create("system", "entropy", NULL, "entropy", NULL, "Available Entropy", "entropy", 1000, update_every, RRDSET_TYPE_LINE);        rrddim_add(st, "entropy", NULL, 1, 1, RRDDIM_ABSOLUTE);    }    else rrdset_next(st);    rrddim_set(st, "entropy", entropy);    rrdset_done(st);    return 0;}
开发者ID:rlugojr,项目名称:netdata,代码行数:29,


示例6: savememory

int savememory(const char *filename, void *mem, size_t size) {    char tmpfilename[FILENAME_MAX + 1];    snprintfz(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long) getpid());    int fd = open(tmpfilename, O_RDWR | O_CREAT | O_NOATIME, 0664);    if (fd < 0) {        error("Cannot create/open file '%s'.", filename);        return -1;    }    if (write(fd, mem, size) != (ssize_t) size) {        error("Cannot write to file '%s' %ld bytes.", filename, (long) size);        close(fd);        return -1;    }    close(fd);    if (rename(tmpfilename, filename)) {        error("Cannot rename '%s' to '%s'", tmpfilename, filename);        return -1;    }    return 0;}
开发者ID:johan--,项目名称:netdata,代码行数:26,


示例7: rrddim_set_name

void rrddim_set_name(RRDSET *st, RRDDIM *rd, const char *name){	debug(D_RRD_CALLS, "rrddim_set_name() %s.%s", st->name, rd->name);	char varname[CONFIG_MAX_NAME + 1];	snprintfz(varname, CONFIG_MAX_NAME, "dim %s name", rd->id);	config_set_default(st->id, varname, name);}
开发者ID:4224657,项目名称:netdata,代码行数:8,


示例8: log_init

void log_init(void) {    char filename[FILENAME_MAX + 1];    snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);    stdout_filename    = config_get(CONFIG_SECTION_GLOBAL, "debug log",  filename);    snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);    stderr_filename    = config_get(CONFIG_SECTION_GLOBAL, "error log",  filename);    snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);    stdaccess_filename = config_get(CONFIG_SECTION_GLOBAL, "access log", filename);    error_log_throttle_period_backup =    error_log_throttle_period = config_get_number(CONFIG_SECTION_GLOBAL, "errors flood protection period", error_log_throttle_period);    error_log_errors_per_period = (unsigned long)config_get_number(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection", (long long int)error_log_errors_per_period);    setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get(CONFIG_SECTION_GLOBAL, "errors flood protection period"    , ""), 1);    setenv("NETDATA_ERRORS_PER_PERIOD",      config_get(CONFIG_SECTION_GLOBAL, "errors to trigger flood protection", ""), 1);}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:18,


示例9: get_system_cpus

long get_system_cpus(void) {    processors = 1;    #ifdef __APPLE__        int32_t tmp_processors;        if (unlikely(GETSYSCTL_BY_NAME("hw.logicalcpu", tmp_processors))) {            error("Assuming system has %d processors.", processors);        } else {            processors = tmp_processors;        }        return processors;    #elif __FreeBSD__        int32_t tmp_processors;        if (unlikely(GETSYSCTL_BY_NAME("hw.ncpu", tmp_processors))) {            error("Assuming system has %d processors.", processors);        } else {            processors = tmp_processors;        }        return processors;    #else    char filename[FILENAME_MAX + 1];    snprintfz(filename, FILENAME_MAX, "%s/proc/stat", netdata_configured_host_prefix);    procfile *ff = procfile_open(filename, NULL, PROCFILE_FLAG_DEFAULT);    if(!ff) {        error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);        return processors;    }    ff = procfile_readall(ff);    if(!ff) {        error("Cannot open file '%s'. Assuming system has %d processors.", filename, processors);        return processors;    }    processors = 0;    unsigned int i;    for(i = 0; i < procfile_lines(ff); i++) {        if(!procfile_linewords(ff, i)) continue;        if(strncmp(procfile_lineword(ff, i, 0), "cpu", 3) == 0) processors++;    }    processors--;    if(processors < 1) processors = 1;    procfile_close(ff);    debug(D_SYSTEM, "System has %d processors.", processors);    return processors;    #endif /* __APPLE__, __FreeBSD__ */}
开发者ID:tvieira,项目名称:netdata,代码行数:57,


示例10: find_all_mc

static void find_all_mc() {    char name[FILENAME_MAX + 1];    snprintfz(name, FILENAME_MAX, "%s%s", netdata_configured_host_prefix, "/sys/devices/system/edac/mc");    char *dirname = config_get("plugin:proc:/sys/devices/system/edac/mc", "directory to monitor", name);    DIR *dir = opendir(dirname);    if(unlikely(!dir)) {        error("Cannot read ECC memory errors directory '%s'", dirname);        return;    }    struct dirent *de = NULL;    while((de = readdir(dir))) {        if(de->d_type == DT_DIR && de->d_name[0] == 'm' && de->d_name[1] == 'c' && isdigit(de->d_name[2])) {            struct mc *m = callocz(1, sizeof(struct mc));            m->name = strdupz(de->d_name);            struct stat st;            snprintfz(name, FILENAME_MAX, "%s/%s/ce_count", dirname, de->d_name);            if(stat(name, &st) != -1)                m->ce_count_filename = strdupz(name);            snprintfz(name, FILENAME_MAX, "%s/%s/ue_count", dirname, de->d_name);            if(stat(name, &st) != -1)                m->ue_count_filename = strdupz(name);            if(!m->ce_count_filename && !m->ue_count_filename) {                freez(m->name);                freez(m);            }            else {                m->next = mc_root;                mc_root = m;            }        }    }    closedir(dir);}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:40,


示例11: rrdsetvar_create_variables

static inline void rrdsetvar_create_variables(RRDSETVAR *rs) {    RRDSET *st = rs->rrdset;    RRDHOST *host = st->rrdhost;    RRDVAR_OPTIONS options = rs->options;    if(rs->options & RRDVAR_OPTION_ALLOCATED)        options &= ~ RRDVAR_OPTION_ALLOCATED;    // ------------------------------------------------------------------------    // free the old ones (if any)    rrdsetvar_free_variables(rs);    // ------------------------------------------------------------------------    // KEYS    char buffer[RRDVAR_MAX_LENGTH + 1];    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->id, rs->variable);    rs->key_fullid = strdupz(buffer);    snprintfz(buffer, RRDVAR_MAX_LENGTH, "%s.%s", st->name, rs->variable);    rs->key_fullname = strdupz(buffer);    // ------------------------------------------------------------------------    // CHART    rs->var_local       = rrdvar_create_and_index("local",  &st->rrdvar_root_index, rs->variable, rs->type, options, rs->value);    // ------------------------------------------------------------------------    // FAMILY    rs->var_family      = rrdvar_create_and_index("family", &st->rrdfamily->rrdvar_root_index, rs->key_fullid,   rs->type, options, rs->value);    rs->var_family_name = rrdvar_create_and_index("family", &st->rrdfamily->rrdvar_root_index, rs->key_fullname, rs->type, options, rs->value);    // ------------------------------------------------------------------------    // HOST    rs->var_host        = rrdvar_create_and_index("host",   &host->rrdvar_root_index, rs->key_fullid,   rs->type, options, rs->value);    rs->var_host_name   = rrdvar_create_and_index("host",   &host->rrdvar_root_index, rs->key_fullname, rs->type, options, rs->value);}
开发者ID:baidjay,项目名称:netdata,代码行数:37,


示例12: set_global_environment

void set_global_environment() {    {        char b[16];        snprintfz(b, 15, "%d", default_rrd_update_every);        setenv("NETDATA_UPDATE_EVERY", b, 1);    }    setenv("NETDATA_HOSTNAME"   , netdata_configured_hostname, 1);    setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir),  1);    setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);    setenv("NETDATA_WEB_DIR"    , verify_required_directory(netdata_configured_web_dir),     1);    setenv("NETDATA_CACHE_DIR"  , verify_required_directory(netdata_configured_cache_dir),   1);    setenv("NETDATA_LIB_DIR"    , verify_required_directory(netdata_configured_varlib_dir),  1);    setenv("NETDATA_LOG_DIR"    , verify_required_directory(netdata_configured_log_dir),     1);    setenv("HOME"               , verify_required_directory(netdata_configured_home_dir),    1);    setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);    get_system_timezone();    // set the path we need    char path[1024 + 1], *p = getenv("PATH");    if(!p) p = "/bin:/usr/bin";    snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");    setenv("PATH", config_get(CONFIG_SECTION_PLUGINS, "PATH environment variable", path), 1);    // python options    p = getenv("PYTHONPATH");    if(!p) p = "";    setenv("PYTHONPATH", config_get(CONFIG_SECTION_PLUGINS, "PYTHONPATH environment variable", p), 1);    // disable buffering for python plugins    setenv("PYTHONUNBUFFERED", "1", 1);    // switch to standard locale for plugins    setenv("LC_ALL", "C", 1);}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:36,


示例13: rrdset_set_name

void rrdset_set_name(RRDSET *st, const char *name){	debug(D_RRD_CALLS, "rrdset_set_name() old: %s, new: %s", st->name, name);	if(st->name) rrdset_index_del_name(st);	char b[CONFIG_MAX_VALUE + 1];	char n[RRD_ID_LENGTH_MAX + 1];	snprintfz(n, RRD_ID_LENGTH_MAX, "%s.%s", st->type, name);	rrdset_strncpyz_name(b, n, CONFIG_MAX_VALUE);	st->name = config_get(st->id, "name", b);	st->hash_name = simple_hash(st->name);	rrdset_index_add_name(st);}
开发者ID:4224657,项目名称:netdata,代码行数:16,


示例14: add_listen_socket

static inline int add_listen_socket(int fd, const char *ip, int port) {    if(listen_fds_count >= MAX_LISTEN_FDS) {        error("Too many listening sockets. Failed to add listening socket at ip '%s' port %d", ip, port);        close(fd);        return -1;    }    listen_fds[listen_fds_count] = fd;    char buffer[100 + 1];    snprintfz(buffer, 100, "[%s]:%d", ip, port);    listen_fds_names[listen_fds_count] = strdup(buffer);    listen_fds_count++;    return 0;}
开发者ID:4224657,项目名称:netdata,代码行数:16,


示例15: cgroup_get_chart_id

void cgroup_get_chart_id(struct cgroup *cg) {	debug(D_CGROUP, "getting the name of cgroup '%s'", cg->id);	pid_t cgroup_pid;	char buffer[CGROUP_CHARTID_LINE_MAX + 1];	snprintfz(buffer, CGROUP_CHARTID_LINE_MAX, "exec %s '%s'",	         config_get("plugin:cgroups", "script to get cgroup names", PLUGINS_DIR "/cgroup-name.sh"), cg->chart_id);	debug(D_CGROUP, "executing command '%s' for cgroup '%s'", buffer, cg->id);	FILE *fp = mypopen(buffer, &cgroup_pid);	if(!fp) {		error("CGROUP: Cannot popen(/"%s/", /"r/").", buffer);		return;	}	debug(D_CGROUP, "reading from command '%s' for cgroup '%s'", buffer, cg->id);	char *s = fgets(buffer, CGROUP_CHARTID_LINE_MAX, fp);	debug(D_CGROUP, "closing command for cgroup '%s'", cg->id);	mypclose(fp, cgroup_pid);	debug(D_CGROUP, "closed command for cgroup '%s'", cg->id);	if(s && *s && *s != '/n') {		debug(D_CGROUP, "cgroup '%s' should be renamed to '%s'", cg->id, s);		trim(s);		free(cg->chart_title);		cg->chart_title = strdup(s);		if(!cg->chart_title)			fatal("CGROUP: Cannot allocate memory for chart name of cgroup '%s' chart name: '%s'", cg->id, s);		netdata_fix_chart_name(cg->chart_title);		free(cg->chart_id);		cg->chart_id = strdup(s);		if(!cg->chart_id)			fatal("CGROUP: Cannot allocate memory for chart id of cgroup '%s' chart id: '%s'", cg->id, s);		netdata_fix_chart_id(cg->chart_id);		debug(D_CGROUP, "cgroup '%s' renamed to '%s' (title: '%s')", cg->id, cg->chart_id, cg->chart_title);	}	else debug(D_CGROUP, "cgroup '%s' is not to be renamed (will be shown as '%s')", cg->id, cg->chart_id);}
开发者ID:AnnaChernova42,项目名称:netdata,代码行数:44,


示例16: recursively_delete_dir

int recursively_delete_dir(const char *path, const char *reason) {    DIR *dir = opendir(path);    if(!dir) {        error("Cannot read %s directory to be deleted '%s'", reason?reason:"", path);        return -1;    }    int ret = 0;    struct dirent *de = NULL;    while((de = readdir(dir))) {        if(de->d_type == DT_DIR           && (                   (de->d_name[0] == '.' && de->d_name[1] == '/0')                   || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '/0')           ))            continue;        char fullpath[FILENAME_MAX + 1];        snprintfz(fullpath, FILENAME_MAX, "%s/%s", path, de->d_name);        if(de->d_type == DT_DIR) {            int r = recursively_delete_dir(fullpath, reason);            if(r > 0) ret += r;            continue;        }        info("Deleting %s file '%s'", reason?reason:"", fullpath);        if(unlikely(unlink(fullpath) == -1))            error("Cannot delete %s file '%s'", reason?reason:"", fullpath);        else            ret++;    }    info("Deleting empty directory '%s'", path);    if(unlikely(rmdir(path) == -1))        error("Cannot delete empty directory '%s'", path);    else        ret++;    closedir(dir);    return ret;}
开发者ID:tvieira,项目名称:netdata,代码行数:43,


示例17: get_system_pid_max

pid_t get_system_pid_max(void) {    #ifdef __APPLE__        // As we currently do not know a solution to query pid_max from the os        // we use the number defined in bsd/sys/proc_internal.h in XNU sources        pid_max = 99999;        return pid_max;    #elif __FreeBSD__        int32_t tmp_pid_max;        if (unlikely(GETSYSCTL_BY_NAME("kern.pid_max", tmp_pid_max))) {            pid_max = 99999;            error("Assuming system's maximum pid is %d.", pid_max);        } else {            pid_max = tmp_pid_max;        }        return pid_max;    #else    static char read = 0;    if(unlikely(read)) return pid_max;    read = 1;    char filename[FILENAME_MAX + 1];    snprintfz(filename, FILENAME_MAX, "%s/proc/sys/kernel/pid_max", netdata_configured_host_prefix);    unsigned long long max = 0;    if(read_single_number_file(filename, &max) != 0) {        error("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);        return pid_max;    }    if(!max) {        error("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);        return pid_max;    }    pid_max = (pid_t) max;    return pid_max;    #endif /* __APPLE__, __FreeBSD__ */}
开发者ID:tvieira,项目名称:netdata,代码行数:42,


示例18: signal_handler

static void signal_handler(int signo) {    // find the entry in the list    int i;    for(i = 0; signals_waiting[i].action != NETDATA_SIGNAL_END_OF_LIST ; i++) {        if(unlikely(signals_waiting[i].signo == signo)) {            signals_waiting[i].count++;            if(signals_waiting[i].action == NETDATA_SIGNAL_FATAL) {                char buffer[200 + 1];                snprintfz(buffer, 200, "/nSIGNAL HANLDER: received: %s. Oops! This is bad!/n", signals_waiting[i].name);                if(write(STDERR_FILENO, buffer, strlen(buffer)) == -1) {                    // nothing to do - we cannot write but there is no way to complaint about it                    ;                }            }            return;        }    }}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:20,


示例19: unit_test

int unit_test(long delay, long shift){    static int repeat = 0;    repeat++;    char name[101];    snprintfz(name, 100, "unittest-%d-%ld-%ld", repeat, delay, shift);    //debug_flags = 0xffffffff;    rrd_memory_mode = RRD_MEMORY_MODE_RAM;    rrd_update_every = 1;    int do_abs = 1;    int do_inc = 1;    int do_abst = 0;    int do_absi = 0;    RRDSET *st = rrdset_create("netdata", name, name, "netdata", NULL, "Unit Testing", "a value", 1, 1, RRDSET_TYPE_LINE);    st->debug = 1;    RRDDIM *rdabs = NULL;    RRDDIM *rdinc = NULL;    RRDDIM *rdabst = NULL;    RRDDIM *rdabsi = NULL;    if(do_abs) rdabs = rrddim_add(st, "absolute", "absolute", 1, 1, RRDDIM_ABSOLUTE);    if(do_inc) rdinc = rrddim_add(st, "incremental", "incremental", 1, 1, RRDDIM_INCREMENTAL);    if(do_abst) rdabst = rrddim_add(st, "percentage-of-absolute-row", "percentage-of-absolute-row", 1, 1, RRDDIM_PCENT_OVER_ROW_TOTAL);    if(do_absi) rdabsi = rrddim_add(st, "percentage-of-incremental-row", "percentage-of-incremental-row", 1, 1, RRDDIM_PCENT_OVER_DIFF_TOTAL);    long increment = 1000;    collected_number i = 0;    unsigned long c, dimensions = 0;    RRDDIM *rd;    for(rd = st->dimensions ; rd ; rd = rd->next) dimensions++;    for(c = 0; c < 20 ;c++) {        i += increment;        fprintf(stderr, "/n/nLOOP = %lu, DELAY = %ld, VALUE = " COLLECTED_NUMBER_FORMAT "/n", c, delay, i);        if(c) {            rrdset_next_usec_unfiltered(st, delay);        }        if(do_abs) rrddim_set(st, "absolute", i);        if(do_inc) rrddim_set(st, "incremental", i);        if(do_abst) rrddim_set(st, "percentage-of-absolute-row", i);        if(do_absi) rrddim_set(st, "percentage-of-incremental-row", i);        if(!c) {            now_realtime_timeval(&st->last_collected_time);            st->last_collected_time.tv_usec = shift;        }        // prevent it from deleting the dimensions        for(rd = st->dimensions ; rd ; rd = rd->next)            rd->last_collected_time.tv_sec = st->last_collected_time.tv_sec;        rrdset_done(st);    }    unsigned long oincrement = increment;    increment = increment * st->update_every * 1000000 / delay;    fprintf(stderr, "/n/nORIGINAL INCREMENT: %lu, INCREMENT %ld, DELAY %ld, SHIFT %ld/n", oincrement * 10, increment * 10, delay, shift);    int ret = 0;    storage_number sn;    calculated_number cn, v;    for(c = 0 ; c < st->counter ; c++) {        fprintf(stderr, "/nPOSITION: c = %lu, EXPECTED VALUE %lu/n", c, (oincrement + c * increment + increment * (1000000 - shift) / 1000000 )* 10);        for(rd = st->dimensions ; rd ; rd = rd->next) {            sn = rd->values[c];            cn = unpack_storage_number(sn);            fprintf(stderr, "/t %s " CALCULATED_NUMBER_FORMAT " (PACKED AS " STORAGE_NUMBER_FORMAT ")   ->   ", rd->id, cn, sn);            if(rd == rdabs) v =                (     oincrement                    // + (increment * (1000000 - shift) / 1000000)                    + (c + 1) * increment                );            else if(rd == rdinc) v = (c?(increment):(increment * (1000000 - shift) / 1000000));            else if(rd == rdabst) v = oincrement / dimensions / 10;            else if(rd == rdabsi) v = oincrement / dimensions / 10;            else v = 0;            if(v == cn) fprintf(stderr, "passed./n");            else {                fprintf(stderr, "ERROR! (expected " CALCULATED_NUMBER_FORMAT ")/n", v);                ret = 1;            }        }    }    if(ret)        fprintf(stderr, "/n/nUNIT TEST(%ld, %ld) FAILED/n/n", delay, shift);    return ret;}
开发者ID:acecommerce,项目名称:netdata,代码行数:100,


示例20: do_proc_spl_kstat_zfs_arcstats

//.........这里部分代码省略.........        arl_expect(arl_base, "other_size", &arcstats.other_size);        arl_expect(arl_base, "anon_size", &arcstats.anon_size);        arl_expect(arl_base, "anon_evictable_data", &arcstats.anon_evictable_data);        arl_expect(arl_base, "anon_evictable_metadata", &arcstats.anon_evictable_metadata);        arl_expect(arl_base, "mru_size", &arcstats.mru_size);        arl_expect(arl_base, "mru_evictable_data", &arcstats.mru_evictable_data);        arl_expect(arl_base, "mru_evictable_metadata", &arcstats.mru_evictable_metadata);        arl_expect(arl_base, "mru_ghost_size", &arcstats.mru_ghost_size);        arl_expect(arl_base, "mru_ghost_evictable_data", &arcstats.mru_ghost_evictable_data);        arl_expect(arl_base, "mru_ghost_evictable_metadata", &arcstats.mru_ghost_evictable_metadata);        arl_expect(arl_base, "mfu_size", &arcstats.mfu_size);        arl_expect(arl_base, "mfu_evictable_data", &arcstats.mfu_evictable_data);        arl_expect(arl_base, "mfu_evictable_metadata", &arcstats.mfu_evictable_metadata);        arl_expect(arl_base, "mfu_ghost_size", &arcstats.mfu_ghost_size);        arl_expect(arl_base, "mfu_ghost_evictable_data", &arcstats.mfu_ghost_evictable_data);        arl_expect(arl_base, "mfu_ghost_evictable_metadata", &arcstats.mfu_ghost_evictable_metadata);        arl_expect(arl_base, "l2_hits", &arcstats.l2_hits);        arl_expect(arl_base, "l2_misses", &arcstats.l2_misses);        arl_expect(arl_base, "l2_feeds", &arcstats.l2_feeds);        arl_expect(arl_base, "l2_rw_clash", &arcstats.l2_rw_clash);        arl_expect(arl_base, "l2_read_bytes", &arcstats.l2_read_bytes);        arl_expect(arl_base, "l2_write_bytes", &arcstats.l2_write_bytes);        arl_expect(arl_base, "l2_writes_sent", &arcstats.l2_writes_sent);        arl_expect(arl_base, "l2_writes_done", &arcstats.l2_writes_done);        arl_expect(arl_base, "l2_writes_error", &arcstats.l2_writes_error);        arl_expect(arl_base, "l2_writes_lock_retry", &arcstats.l2_writes_lock_retry);        arl_expect(arl_base, "l2_evict_lock_retry", &arcstats.l2_evict_lock_retry);        arl_expect(arl_base, "l2_evict_reading", &arcstats.l2_evict_reading);        arl_expect(arl_base, "l2_evict_l1cached", &arcstats.l2_evict_l1cached);        arl_expect(arl_base, "l2_free_on_write", &arcstats.l2_free_on_write);        arl_expect(arl_base, "l2_cdata_free_on_write", &arcstats.l2_cdata_free_on_write);        arl_expect(arl_base, "l2_abort_lowmem", &arcstats.l2_abort_lowmem);        arl_expect(arl_base, "l2_cksum_bad", &arcstats.l2_cksum_bad);        arl_expect(arl_base, "l2_io_error", &arcstats.l2_io_error);        arl_expect(arl_base, "l2_size", &arcstats.l2_size);        arl_expect(arl_base, "l2_asize", &arcstats.l2_asize);        arl_expect(arl_base, "l2_hdr_size", &arcstats.l2_hdr_size);        arl_expect(arl_base, "l2_compress_successes", &arcstats.l2_compress_successes);        arl_expect(arl_base, "l2_compress_zeros", &arcstats.l2_compress_zeros);        arl_expect(arl_base, "l2_compress_failures", &arcstats.l2_compress_failures);        arl_expect(arl_base, "memory_throttle_count", &arcstats.memory_throttle_count);        arl_expect(arl_base, "duplicate_buffers", &arcstats.duplicate_buffers);        arl_expect(arl_base, "duplicate_buffers_size", &arcstats.duplicate_buffers_size);        arl_expect(arl_base, "duplicate_reads", &arcstats.duplicate_reads);        arl_expect(arl_base, "memory_direct_count", &arcstats.memory_direct_count);        arl_expect(arl_base, "memory_indirect_count", &arcstats.memory_indirect_count);        arl_expect(arl_base, "arc_no_grow", &arcstats.arc_no_grow);        arl_expect(arl_base, "arc_tempreserve", &arcstats.arc_tempreserve);        arl_expect(arl_base, "arc_loaned_bytes", &arcstats.arc_loaned_bytes);        arl_expect(arl_base, "arc_prune", &arcstats.arc_prune);        arl_expect(arl_base, "arc_meta_used", &arcstats.arc_meta_used);        arl_expect(arl_base, "arc_meta_limit", &arcstats.arc_meta_limit);        arl_expect(arl_base, "arc_meta_max", &arcstats.arc_meta_max);        arl_expect(arl_base, "arc_meta_min", &arcstats.arc_meta_min);        arl_expect(arl_base, "arc_need_free", &arcstats.arc_need_free);        arl_expect(arl_base, "arc_sys_free", &arcstats.arc_sys_free);    }    if(unlikely(!ff)) {        char filename[FILENAME_MAX + 1];        snprintfz(filename, FILENAME_MAX, "%s%s", netdata_configured_host_prefix, ZFS_PROC_ARCSTATS);        ff = procfile_open(config_get("plugin:proc:" ZFS_PROC_ARCSTATS, "filename to monitor", filename), " /t:", PROCFILE_FLAG_DEFAULT);        if(unlikely(!ff))            return 1;    }    ff = procfile_readall(ff);    if(unlikely(!ff))        return 0; // we return 0, so that we will retry to open it next time    size_t lines = procfile_lines(ff), l;    arl_begin(arl_base);    for(l = 0; l < lines ;l++) {        size_t words = procfile_linewords(ff, l);        if(unlikely(words < 3)) {            if(unlikely(words)) error("Cannot read " ZFS_PROC_ARCSTATS " line %zu. Expected 3 params, read %zu.", l, words);            continue;        }        const char *key   = procfile_lineword(ff, l, 0);        const char *value = procfile_lineword(ff, l, 2);        if(unlikely(arcstats.l2exist == -1)) {            if(key[0] == 'l' && key[1] == '2' && key[2] == '_')                arcstats.l2exist = 1;        }        if(unlikely(arl_check(arl_base, key, value))) break;    }    if(unlikely(arcstats.l2exist == -1))        arcstats.l2exist = 0;    generate_charts_arcstats("proc", update_every);    generate_charts_arc_summary("proc", update_every);    return 0;}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:101,


示例21: registry_init

int registry_init(void) {    char filename[FILENAME_MAX + 1];    // registry enabled?    if(web_server_mode != WEB_SERVER_MODE_NONE) {        registry.enabled = config_get_boolean(CONFIG_SECTION_REGISTRY, "enabled", 0);    }    else {        info("Registry is disabled - use the central netdata");        config_set_boolean(CONFIG_SECTION_REGISTRY, "enabled", 0);        registry.enabled = 0;    }    // pathnames    snprintfz(filename, FILENAME_MAX, "%s/registry", netdata_configured_varlib_dir);    registry.pathname = config_get(CONFIG_SECTION_REGISTRY, "registry db directory", filename);    if(mkdir(registry.pathname, 0770) == -1 && errno != EEXIST)        fatal("Cannot create directory '%s'.", registry.pathname);    // filenames    snprintfz(filename, FILENAME_MAX, "%s/netdata.public.unique.id", registry.pathname);    registry.machine_guid_filename = config_get(CONFIG_SECTION_REGISTRY, "netdata unique id file", filename);    snprintfz(filename, FILENAME_MAX, "%s/registry.db", registry.pathname);    registry.db_filename = config_get(CONFIG_SECTION_REGISTRY, "registry db file", filename);    snprintfz(filename, FILENAME_MAX, "%s/registry-log.db", registry.pathname);    registry.log_filename = config_get(CONFIG_SECTION_REGISTRY, "registry log file", filename);    // configuration options    registry.save_registry_every_entries = (unsigned long long)config_get_number(CONFIG_SECTION_REGISTRY, "registry save db every new entries", 1000000);    registry.persons_expiration = config_get_number(CONFIG_SECTION_REGISTRY, "registry expire idle persons days", 365) * 86400;    registry.registry_domain = config_get(CONFIG_SECTION_REGISTRY, "registry domain", "");    registry.registry_to_announce = config_get(CONFIG_SECTION_REGISTRY, "registry to announce", "https://registry.my-netdata.io");    registry.hostname = config_get(CONFIG_SECTION_REGISTRY, "registry hostname", netdata_configured_hostname);    registry.verify_cookies_redirects = config_get_boolean(CONFIG_SECTION_REGISTRY, "verify browser cookies support", 1);    setenv("NETDATA_REGISTRY_HOSTNAME", registry.hostname, 1);    setenv("NETDATA_REGISTRY_URL", registry.registry_to_announce, 1);    registry.max_url_length = (size_t)config_get_number(CONFIG_SECTION_REGISTRY, "max URL length", 1024);    if(registry.max_url_length < 10) {        registry.max_url_length = 10;        config_set_number(CONFIG_SECTION_REGISTRY, "max URL length", (long long)registry.max_url_length);    }    registry.max_name_length = (size_t)config_get_number(CONFIG_SECTION_REGISTRY, "max URL name length", 50);    if(registry.max_name_length < 10) {        registry.max_name_length = 10;        config_set_number(CONFIG_SECTION_REGISTRY, "max URL name length", (long long)registry.max_name_length);    }    // initialize entries counters    registry.persons_count = 0;    registry.machines_count = 0;    registry.usages_count = 0;    registry.urls_count = 0;    registry.persons_urls_count = 0;    registry.machines_urls_count = 0;    // initialize memory counters    registry.persons_memory = 0;    registry.machines_memory = 0;    registry.urls_memory = 0;    registry.persons_urls_memory = 0;    registry.machines_urls_memory = 0;    // initialize locks    netdata_mutex_init(&registry.lock);    // create dictionaries    registry.persons = dictionary_create(DICTIONARY_FLAGS);    registry.machines = dictionary_create(DICTIONARY_FLAGS);    avl_init(&registry.registry_urls_root_index, registry_url_compare);    // load the registry database    if(registry.enabled) {        registry_log_open();        registry_db_load();        registry_log_load();        if(unlikely(registry_db_should_be_saved()))            registry_db_save();    }    return 0;}
开发者ID:FedericoCeratto,项目名称:netdata,代码行数:87,


示例22: netdata_thread_cleanup_push

void *tc_main(void *ptr) {    netdata_thread_cleanup_push(tc_main_cleanup, ptr);    struct rusage thread;    char command[FILENAME_MAX + 1];    char *words[PLUGINSD_MAX_WORDS] = { NULL };    uint32_t BEGIN_HASH = simple_hash("BEGIN");    uint32_t END_HASH = simple_hash("END");    uint32_t QDISC_HASH = simple_hash("qdisc");    uint32_t CLASS_HASH = simple_hash("class");    uint32_t SENT_HASH = simple_hash("Sent");    uint32_t LENDED_HASH = simple_hash("lended:");    uint32_t TOKENS_HASH = simple_hash("tokens:");    uint32_t SETDEVICENAME_HASH = simple_hash("SETDEVICENAME");    uint32_t SETDEVICEGROUP_HASH = simple_hash("SETDEVICEGROUP");    uint32_t SETCLASSNAME_HASH = simple_hash("SETCLASSNAME");    uint32_t WORKTIME_HASH = simple_hash("WORKTIME");#ifdef DETACH_PLUGINS_FROM_NETDATA    uint32_t MYPID_HASH = simple_hash("MYPID");#endif    uint32_t first_hash;    snprintfz(command, TC_LINE_MAX, "%s/tc-qos-helper.sh", netdata_configured_primary_plugins_dir);    char *tc_script = config_get("plugin:tc", "script to run to get tc values", command);    while(!netdata_exit) {        FILE *fp;        struct tc_device *device = NULL;        struct tc_class *class = NULL;        snprintfz(command, TC_LINE_MAX, "exec %s %d", tc_script, localhost->rrd_update_every);        debug(D_TC_LOOP, "executing '%s'", command);        fp = mypopen(command, (pid_t *)&tc_child_pid);        if(unlikely(!fp)) {            error("TC: Cannot popen(/"%s/", /"r/").", command);            goto cleanup;        }        char buffer[TC_LINE_MAX+1] = "";        while(fgets(buffer, TC_LINE_MAX, fp) != NULL) {            if(unlikely(netdata_exit)) break;            buffer[TC_LINE_MAX] = '/0';            // debug(D_TC_LOOP, "TC: read '%s'", buffer);            tc_split_words(buffer, words, PLUGINSD_MAX_WORDS);            if(unlikely(!words[0] || !*words[0])) {                // debug(D_TC_LOOP, "empty line");                continue;            }            // else debug(D_TC_LOOP, "First word is '%s'", words[0]);            first_hash = simple_hash(words[0]);            if(unlikely(device && ((first_hash == CLASS_HASH && strcmp(words[0], "class") == 0) ||  (first_hash == QDISC_HASH && strcmp(words[0], "qdisc") == 0)))) {                // debug(D_TC_LOOP, "CLASS line on class id='%s', parent='%s', parentid='%s', leaf='%s', leafid='%s'", words[2], words[3], words[4], words[5], words[6]);                char *type     = words[1];  // the class/qdisc type: htb, fq_codel, etc                char *id       = words[2];  // the class/qdisc major:minor                char *parent   = words[3];  // the word 'parent' or 'root'                char *parentid = words[4];  // parentid                char *leaf     = words[5];  // the word 'leaf'                char *leafid   = words[6];  // leafid                int parent_is_root = 0;                int parent_is_parent = 0;                if(likely(parent)) {                    parent_is_parent = !strcmp(parent, "parent");                    if(!parent_is_parent)                        parent_is_root = !strcmp(parent, "root");                }                if(likely(type && id && (parent_is_root || parent_is_parent))) {                    char qdisc = 0;                    if(first_hash == QDISC_HASH) {                        qdisc = 1;                        if(!strcmp(type, "ingress")) {                            // we don't want to get the ingress qdisc                            // there should be an IFB interface for this                            class = NULL;                            continue;                        }                        if(parent_is_parent && parentid) {                            // eliminate the minor number from parentid                            // why: parentid is the id of the parent class                            // but major: is also the id of the parent qdisc                            char *s = parentid;                            while(*s && *s != ':') s++;                            if(*s == ':') s[1] = '/0';                        }//.........这里部分代码省略.........
开发者ID:firehol,项目名称:netdata,代码行数:101,


示例23: tc_device_commit

static inline void tc_device_commit(struct tc_device *d) {    static int enable_new_interfaces = -1, enable_bytes = -1, enable_packets = -1, enable_dropped = -1, enable_tokens = -1, enable_ctokens = -1, enabled_all_classes_qdiscs = -1;    if(unlikely(enable_new_interfaces == -1)) {        enable_new_interfaces      = config_get_boolean_ondemand("plugin:tc", "enable new interfaces detected at runtime", CONFIG_BOOLEAN_YES);        enable_bytes               = config_get_boolean_ondemand("plugin:tc", "enable traffic charts for all interfaces", CONFIG_BOOLEAN_AUTO);        enable_packets             = config_get_boolean_ondemand("plugin:tc", "enable packets charts for all interfaces", CONFIG_BOOLEAN_AUTO);        enable_dropped             = config_get_boolean_ondemand("plugin:tc", "enable dropped charts for all interfaces", CONFIG_BOOLEAN_AUTO);        enable_tokens              = config_get_boolean_ondemand("plugin:tc", "enable tokens charts for all interfaces", CONFIG_BOOLEAN_NO);        enable_ctokens             = config_get_boolean_ondemand("plugin:tc", "enable ctokens charts for all interfaces", CONFIG_BOOLEAN_NO);        enabled_all_classes_qdiscs = config_get_boolean_ondemand("plugin:tc", "enable show all classes and qdiscs for all interfaces", CONFIG_BOOLEAN_NO);    }    if(unlikely(d->enabled == (char)-1)) {        char var_name[CONFIG_MAX_NAME + 1];        snprintfz(var_name, CONFIG_MAX_NAME, "qos for %s", d->id);        d->enabled                    = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_new_interfaces);        snprintfz(var_name, CONFIG_MAX_NAME, "traffic chart for %s", d->id);        d->enabled_bytes              = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_bytes);        snprintfz(var_name, CONFIG_MAX_NAME, "packets chart for %s", d->id);        d->enabled_packets            = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_packets);        snprintfz(var_name, CONFIG_MAX_NAME, "dropped packets chart for %s", d->id);        d->enabled_dropped            = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_dropped);        snprintfz(var_name, CONFIG_MAX_NAME, "tokens chart for %s", d->id);        d->enabled_tokens             = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_tokens);        snprintfz(var_name, CONFIG_MAX_NAME, "ctokens chart for %s", d->id);        d->enabled_ctokens            = (char)config_get_boolean_ondemand("plugin:tc", var_name, enable_ctokens);        snprintfz(var_name, CONFIG_MAX_NAME, "show all classes for %s", d->id);        d->enabled_all_classes_qdiscs = (char)config_get_boolean_ondemand("plugin:tc", var_name, enabled_all_classes_qdiscs);    }    // we only need to add leaf classes    struct tc_class *c, *x /*, *root = NULL */;    unsigned long long bytes_sum = 0, packets_sum = 0, dropped_sum = 0, tokens_sum = 0, ctokens_sum = 0;    int active_nodes = 0, updated_classes = 0, updated_qdiscs = 0;    // prepare all classes    // we set reasonable defaults for the rest of the code below    for(c = d->classes ; c ; c = c->next) {        c->render = 0;          // do not render this class        c->isleaf = 1;          // this is a leaf class        c->hasparent = 0;       // without a parent        if(unlikely(!c->updated))            c->unupdated++;     // increase its unupdated counter        else {            c->unupdated = 0;   // reset its unupdated counter            // count how many of each kind            if(c->isqdisc)                updated_qdiscs++;            else                updated_classes++;        }    }    if(unlikely(!d->enabled || (!updated_classes && !updated_qdiscs))) {        debug(D_TC_LOOP, "TC: Ignoring TC device '%s'. It is not enabled/updated.", d->name?d->name:d->id);        tc_device_classes_cleanup(d);        return;    }    if(unlikely(updated_classes && updated_qdiscs)) {        error("TC: device '%s' has active both classes (%d) and qdiscs (%d). Will render only qdiscs.", d->id, updated_classes, updated_qdiscs);        // set all classes to !updated        for(c = d->classes ; c ; c = c->next)            if(unlikely(!c->isqdisc && c->updated))                c->updated = 0;        updated_classes = 0;    }    // mark the classes as leafs and parents    //    // TC is hierarchical:    //  - classes can have other classes in them    //  - the same is true for qdiscs (i.e. qdiscs have classes, that have other qdiscs)    //    // we need to present a chart with leaf nodes only, so that the sum    // of all dimensions of the chart, will be the total utilization    // of the interface.    //    // here we try to find the ones we need to report    // by default all nodes are marked with: isleaf = 1 (see above)    //    // so, here we remove the isleaf flag from nodes in the middle    // and we add the hasparent flag to leaf nodes we found their parent    if(likely(!d->enabled_all_classes_qdiscs)) {        for(c = d->classes; c; c = c->next) {            if(unlikely(!c->updated)) continue;//.........这里部分代码省略.........
开发者ID:firehol,项目名称:netdata,代码行数:101,


示例24: main

//.........这里部分代码省略.........							debug_flags = strtoull(optarg, NULL, 0);						}					}					break;				default: /* ? */					help(1);					break;			}		}	}	if(!config_loaded) load_config(NULL, 0);	// prepare configuration environment variables for the plugins	setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);	setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);	setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);	setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);	setenv("NETDATA_LIB_DIR"    , config_get("global", "lib directory"      , VARLIB_DIR) , 1);	setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);	setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);	setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);	// disable buffering for python plugins	setenv("PYTHONUNBUFFERED", "1", 1);	// avoid flood calls to stat(/etc/localtime)	// http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux	setenv("TZ", ":/etc/localtime", 0);	{		char path[1024 + 1], *p = getenv("PATH");		if(!p) p = "/bin:/usr/bin";		snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");		setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);	}	// cd to /tmp to avoid any plugins writing files at random places	if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");	char *input_log_file = NULL;	char *output_log_file = NULL;	char *error_log_file = NULL;	char *access_log_file = NULL;	char *user = NULL;	{		char *flags = config_get("global", "debug flags",  "0x00000000");		setenv("NETDATA_DEBUG_FLAGS", flags, 1);		debug_flags = strtoull(flags, NULL, 0);		debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);		if(debug_flags != 0) {			struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };			if(setrlimit(RLIMIT_CORE, &rl) != 0)				info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);		}		// --------------------------------------------------------------------#ifdef MADV_MERGEABLE		enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);#else#warning "Kernel memory deduplication (KSM) is not available"#endif
开发者ID:4224657,项目名称:netdata,代码行数:67,


示例25: do_proc_interrupts

int do_proc_interrupts(int update_every, usec_t dt) {    (void)dt;    static procfile *ff = NULL;    static int cpus = -1, do_per_core = -1;    struct interrupt *irrs = NULL;    if(unlikely(do_per_core == -1))        do_per_core = config_get_boolean("plugin:proc:/proc/interrupts", "interrupts per core", 1);    if(unlikely(!ff)) {        char filename[FILENAME_MAX + 1];        snprintfz(filename, FILENAME_MAX, "%s%s", global_host_prefix, "/proc/interrupts");        ff = procfile_open(config_get("plugin:proc:/proc/interrupts", "filename to monitor", filename), " /t", PROCFILE_FLAG_DEFAULT);    }    if(unlikely(!ff))        return 1;    ff = procfile_readall(ff);    if(unlikely(!ff))        return 0; // we return 0, so that we will retry to open it next time    uint32_t lines = procfile_lines(ff), l;    uint32_t words = procfile_linewords(ff, 0);    if(unlikely(!lines)) {        error("Cannot read /proc/interrupts, zero lines reported.");        return 1;    }    // find how many CPUs are there    if(unlikely(cpus == -1)) {        uint32_t w;        cpus = 0;        for(w = 0; w < words ; w++) {            if(likely(strncmp(procfile_lineword(ff, 0, w), "CPU", 3) == 0))                cpus++;        }    }    if(unlikely(!cpus)) {        error("PLUGIN: PROC_INTERRUPTS: Cannot find the number of CPUs in /proc/interrupts");        return 1;    }    // allocate the size we need;    irrs = get_interrupts_array(lines, cpus);    irrs[0].used = 0;    // loop through all lines    for(l = 1; l < lines ;l++) {        struct interrupt *irr = irrindex(irrs, l, cpus);        irr->used = 0;        irr->total = 0;        words = procfile_linewords(ff, l);        if(unlikely(!words)) continue;        irr->id = procfile_lineword(ff, l, 0);        if(unlikely(!irr->id || !irr->id[0])) continue;        int idlen = strlen(irr->id);        if(unlikely(irr->id[idlen - 1] == ':'))            irr->id[idlen - 1] = '/0';        int c;        for(c = 0; c < cpus ;c++) {            if(likely((c + 1) < (int)words))                irr->cpu[c].value = strtoull(procfile_lineword(ff, l, (uint32_t)(c + 1)), NULL, 10);            else                irr->cpu[c].value = 0;            irr->total += irr->cpu[c].value;        }        if(unlikely(isdigit(irr->id[0]) && (uint32_t)(cpus + 2) < words)) {            strncpyz(irr->name, procfile_lineword(ff, l, words - 1), MAX_INTERRUPT_NAME);            int nlen = strlen(irr->name);            int idlen = strlen(irr->id);            if(likely(nlen + 1 + idlen <= MAX_INTERRUPT_NAME)) {                irr->name[nlen] = '_';                strncpyz(&irr->name[nlen + 1], irr->id, MAX_INTERRUPT_NAME - nlen - 1);            }            else {                irr->name[MAX_INTERRUPT_NAME - idlen - 1] = '_';                strncpyz(&irr->name[MAX_INTERRUPT_NAME - idlen], irr->id, idlen);            }        }        else {            strncpyz(irr->name, irr->id, MAX_INTERRUPT_NAME);        }        irr->used = 1;    }    RRDSET *st;    // --------------------------------------------------------------------    st = rrdset_find_bytype("system", "interrupts");    if(unlikely(!st)) st = rrdset_create("system", "interrupts", NULL, "interrupts", NULL, "System interrupts", "interrupts/s", 1000, update_every, RRDSET_TYPE_STACKED);//.........这里部分代码省略.........
开发者ID:acecommerce,项目名称:netdata,代码行数:101,


示例26: main

//.........这里部分代码省略.........    {        // --------------------------------------------------------------------        // get the debugging flags from the configuration file        char *flags = config_get(CONFIG_SECTION_GLOBAL, "debug flags",  "0x0000000000000000");        setenv("NETDATA_DEBUG_FLAGS", flags, 1);        debug_flags = strtoull(flags, NULL, 0);        debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);        if(debug_flags != 0) {            struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };            if(setrlimit(RLIMIT_CORE, &rl) != 0)                error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");#ifdef HAVE_SYS_PRCTL_H            prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);#endif        }        // --------------------------------------------------------------------        // get log filenames and settings        log_init();        error_log_limit_unlimited();        // --------------------------------------------------------------------        // load stream.conf        {            char filename[FILENAME_MAX + 1];            snprintfz(filename, FILENAME_MAX, "%s/stream.conf", netdata_configured_config_dir);            appconfig_load(&stream_config, filename, 0);        }        // --------------------------------------------------------------------        // setup process signals        // block signals while initializing threads.        // this causes the threads to block signals.        signals_block();        // setup the signals we want to use        signals_init();        // setup threads configs        default_stacksize = netdata_threads_init();        // --------------------------------------------------------------------        // check which threads are enabled and initialize them        for (i = 0; static_threads[i].name != NULL ; i++) {            struct netdata_static_thread *st = &static_threads[i];            if(st->config_name)                st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);            if(st->enabled && st->init_routine)                st->init_routine();        }
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:65,


示例27: get_netdata_configured_variables

static void get_netdata_configured_variables() {    backwards_compatible_config();    // ------------------------------------------------------------------------    // get the hostname    char buf[HOSTNAME_MAX + 1];    if(gethostname(buf, HOSTNAME_MAX) == -1)        error("Cannot get machine hostname.");    netdata_configured_hostname = config_get(CONFIG_SECTION_GLOBAL, "hostname", buf);    debug(D_OPTIONS, "hostname set to '%s'", netdata_configured_hostname);    // ------------------------------------------------------------------------    // get default database size    default_rrd_history_entries = (int) config_get_number(CONFIG_SECTION_GLOBAL, "history", align_entries_to_pagesize(default_rrd_memory_mode, RRD_DEFAULT_HISTORY_ENTRIES));    long h = align_entries_to_pagesize(default_rrd_memory_mode, default_rrd_history_entries);    if(h != default_rrd_history_entries) {        config_set_number(CONFIG_SECTION_GLOBAL, "history", h);        default_rrd_history_entries = (int)h;    }    if(default_rrd_history_entries < 5 || default_rrd_history_entries > RRD_HISTORY_ENTRIES_MAX) {        error("Invalid history entries %d given. Defaulting to %d.", default_rrd_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);        default_rrd_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;    }    // ------------------------------------------------------------------------    // get default database update frequency    default_rrd_update_every = (int) config_get_number(CONFIG_SECTION_GLOBAL, "update every", UPDATE_EVERY);    if(default_rrd_update_every < 1 || default_rrd_update_every > 600) {        error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", default_rrd_update_every, UPDATE_EVERY_MAX);        default_rrd_update_every = UPDATE_EVERY;    }    // ------------------------------------------------------------------------    // get system paths    netdata_configured_config_dir  = config_get(CONFIG_SECTION_GLOBAL, "config directory",    CONFIG_DIR);    netdata_configured_log_dir     = config_get(CONFIG_SECTION_GLOBAL, "log directory",       LOG_DIR);    netdata_configured_web_dir     = config_get(CONFIG_SECTION_GLOBAL, "web files directory", WEB_DIR);    netdata_configured_cache_dir   = config_get(CONFIG_SECTION_GLOBAL, "cache directory",     CACHE_DIR);    netdata_configured_varlib_dir  = config_get(CONFIG_SECTION_GLOBAL, "lib directory",       VARLIB_DIR);    netdata_configured_home_dir    = config_get(CONFIG_SECTION_GLOBAL, "home directory",      CACHE_DIR);    {        char plugins_dirs[(FILENAME_MAX * 2) + 1];        snprintfz(plugins_dirs, FILENAME_MAX * 2, "/"%s/" /"%s/custom-plugins.d/"", PLUGINS_DIR, CONFIG_DIR);        netdata_configured_plugins_dir_base = strdupz(config_get(CONFIG_SECTION_GLOBAL, "plugins directory",  plugins_dirs));        quoted_strings_splitter(netdata_configured_plugins_dir_base, plugin_directories, PLUGINSD_MAX_DIRECTORIES, config_isspace);        netdata_configured_plugins_dir = plugin_directories[0];    }    // ------------------------------------------------------------------------    // get default memory mode for the database    default_rrd_memory_mode = rrd_memory_mode_id(config_get(CONFIG_SECTION_GLOBAL, "memory mode", rrd_memory_mode_name(default_rrd_memory_mode)));    // ------------------------------------------------------------------------    netdata_configured_host_prefix = config_get(CONFIG_SECTION_GLOBAL, "host access prefix", "");    verify_netdata_host_prefix();    // --------------------------------------------------------------------    // get KSM settings#ifdef MADV_MERGEABLE    enable_ksm = config_get_boolean(CONFIG_SECTION_GLOBAL, "memory deduplication (ksm)", enable_ksm);#endif    // --------------------------------------------------------------------    // get various system parameters    get_system_HZ();    get_system_cpus();    get_system_pid_max();}
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:80,


示例28: benchmark_storage_number

void benchmark_storage_number(int loop, int multiplier) {    int i, j;    calculated_number n, d;    storage_number s;    unsigned long long user, system, total, mine, their;    char buffer[100];    struct rusage now, last;    fprintf(stderr, "/n/nBenchmarking %d numbers, please wait.../n/n", loop);    // ------------------------------------------------------------------------    fprintf(stderr, "SYSTEM  LONG DOUBLE    SIZE: %zu bytes/n", sizeof(calculated_number));    fprintf(stderr, "NETDATA FLOATING POINT SIZE: %zu bytes/n", sizeof(storage_number));    mine = (calculated_number)sizeof(storage_number) * (calculated_number)loop;    their = (calculated_number)sizeof(calculated_number) * (calculated_number)loop;    if(mine > their) {        fprintf(stderr, "/nNETDATA NEEDS %0.2Lf TIMES MORE MEMORY. Sorry!/n", (long double)(mine / their));    }    else {        fprintf(stderr, "/nNETDATA INTERNAL FLOATING POINT ARITHMETICS NEEDS %0.2Lf TIMES LESS MEMORY./n", (long double)(their / mine));    }    fprintf(stderr, "/nNETDATA FLOATING POINT/n");    fprintf(stderr, "MIN POSITIVE VALUE " CALCULATED_NUMBER_FORMAT "/n", (calculated_number)STORAGE_NUMBER_POSITIVE_MIN);    fprintf(stderr, "MAX POSITIVE VALUE " CALCULATED_NUMBER_FORMAT "/n", (calculated_number)STORAGE_NUMBER_POSITIVE_MAX);    fprintf(stderr, "MIN NEGATIVE VALUE " CALCULATED_NUMBER_FORMAT "/n", (calculated_number)STORAGE_NUMBER_NEGATIVE_MIN);    fprintf(stderr, "MAX NEGATIVE VALUE " CALCULATED_NUMBER_FORMAT "/n", (calculated_number)STORAGE_NUMBER_NEGATIVE_MAX);    fprintf(stderr, "Maximum accuracy loss: " CALCULATED_NUMBER_FORMAT "%%/n/n/n", (calculated_number)ACCURACY_LOSS);    // ------------------------------------------------------------------------    fprintf(stderr, "INTERNAL LONG DOUBLE PRINTING: ");    getrusage(RUSAGE_SELF, &last);    // do the job    for(j = 1; j < 11 ;j++) {        n = STORAGE_NUMBER_POSITIVE_MIN * j;        for(i = 0; i < loop ;i++) {            n *= multiplier;            if(n > STORAGE_NUMBER_POSITIVE_MAX) n = STORAGE_NUMBER_POSITIVE_MIN;            print_calculated_number(buffer, n);        }    }    getrusage(RUSAGE_SELF, &now);    user   = now.ru_utime.tv_sec * 1000000ULL + now.ru_utime.tv_usec - last.ru_utime.tv_sec * 1000000ULL + last.ru_utime.tv_usec;    system = now.ru_stime.tv_sec * 1000000ULL + now.ru_stime.tv_usec - last.ru_stime.tv_sec * 1000000ULL + last.ru_stime.tv_usec;    total  = user + system;    mine = total;    fprintf(stderr, "user %0.5Lf, system %0.5Lf, total %0.5Lf/n", (long double)(user / 1000000.0), (long double)(system / 1000000.0), (long double)(total / 1000000.0));    // ------------------------------------------------------------------------    fprintf(stderr, "SYSTEM   LONG DOUBLE PRINTING: ");    getrusage(RUSAGE_SELF, &last);    // do the job    for(j = 1; j < 11 ;j++) {        n = STORAGE_NUMBER_POSITIVE_MIN * j;        for(i = 0; i < loop ;i++) {            n *= multiplier;            if(n > STORAGE_NUMBER_POSITIVE_MAX) n = STORAGE_NUMBER_POSITIVE_MIN;            snprintfz(buffer, 100, CALCULATED_NUMBER_FORMAT, n);        }    }    getrusage(RUSAGE_SELF, &now);    user   = now.ru_utime.tv_sec * 1000000ULL + now.ru_utime.tv_usec - last.ru_utime.tv_sec * 1000000ULL + last.ru_utime.tv_usec;    system = now.ru_stime.tv_sec * 1000000ULL + now.ru_stime.tv_usec - last.ru_stime.tv_sec * 1000000ULL + last.ru_stime.tv_usec;    total  = user + system;    their = total;    fprintf(stderr, "user %0.5Lf, system %0.5Lf, total %0.5Lf/n", (long double)(user / 1000000.0), (long double)(system / 1000000.0), (long double)(total / 1000000.0));    if(mine > total) {        fprintf(stderr, "NETDATA CODE IS SLOWER %0.2Lf %%/n", (long double)(mine * 100.0 / their - 100.0));    }    else {        fprintf(stderr, "NETDATA CODE IS  F A S T E R  %0.2Lf %%/n", (long double)(their * 100.0 / mine - 100.0));    }    // ------------------------------------------------------------------------    fprintf(stderr, "/nINTERNAL LONG DOUBLE PRINTING WITH PACK / UNPACK: ");    getrusage(RUSAGE_SELF, &last);    // do the job    for(j = 1; j < 11 ;j++) {        n = STORAGE_NUMBER_POSITIVE_MIN * j;        for(i = 0; i < loop ;i++) {//.........这里部分代码省略.........
开发者ID:acecommerce,项目名称:netdata,代码行数:101,


示例29: run_test

int run_test(struct test *test){    fprintf(stderr, "/nRunning test '%s':/n%s/n", test->name, test->description);    rrd_memory_mode = RRD_MEMORY_MODE_RAM;    rrd_update_every = test->update_every;    char name[101];    snprintfz(name, 100, "unittest-%s", test->name);    // create the chart    RRDSET *st = rrdset_create("netdata", name, name, "netdata", NULL, "Unit Testing", "a value", 1, test->update_every, RRDSET_TYPE_LINE);    RRDDIM *rd = rrddim_add(st, "dim1", NULL, test->multiplier, test->divisor, test->algorithm);        RRDDIM *rd2 = NULL;    if(test->feed2)        rd2 = rrddim_add(st, "dim2", NULL, test->multiplier, test->divisor, test->algorithm);    st->debug = 1;    // feed it with the test data    time_t time_now = 0, time_start = now_realtime_sec();    unsigned long c;    collected_number last = 0;    for(c = 0; c < test->feed_entries; c++) {        if(debug_flags) fprintf(stderr, "/n/n");        if(c) {            time_now += test->feed[c].microseconds;            fprintf(stderr, "    > %s: feeding position %lu, after %0.3f seconds (%0.3f seconds from start), delta " CALCULATED_NUMBER_FORMAT ", rate " CALCULATED_NUMBER_FORMAT "/n",                 test->name, c+1,                (float)test->feed[c].microseconds / 1000000.0,                (float)time_now / 1000000.0,                ((calculated_number)test->feed[c].value - (calculated_number)last) * (calculated_number)test->multiplier / (calculated_number)test->divisor,                (((calculated_number)test->feed[c].value - (calculated_number)last) * (calculated_number)test->multiplier / (calculated_number)test->divisor) / (calculated_number)test->feed[c].microseconds * (calculated_number)1000000);            rrdset_next_usec_unfiltered(st, test->feed[c].microseconds);        }        else {            fprintf(stderr, "    > %s: feeding position %lu/n", test->name, c+1);        }        fprintf(stderr, "       >> %s with value " COLLECTED_NUMBER_FORMAT "/n", rd->name, test->feed[c].value);        rrddim_set(st, "dim1", test->feed[c].value);        last = test->feed[c].value;        if(rd2) {            fprintf(stderr, "       >> %s with value " COLLECTED_NUMBER_FORMAT "/n", rd2->name, test->feed2[c]);            rrddim_set(st, "dim2", test->feed2[c]);        }        rrdset_done(st);        // align the first entry to second boundary        if(!c) {            fprintf(stderr, "    > %s: fixing first collection time to be %llu microseconds to second boundary/n", test->name, test->feed[c].microseconds);            rd->last_collected_time.tv_usec = st->last_collected_time.tv_usec = st->last_updated.tv_usec = test->feed[c].microseconds;            // time_start = st->last_collected_time.tv_sec;        }    }    // check the result    int errors = 0;    if(st->counter != test->result_entries) {        fprintf(stderr, "    %s stored %lu entries, but we were expecting %lu, ### E R R O R ###/n", test->name, st->counter, test->result_entries);        errors++;    }    unsigned long max = (st->counter < test->result_entries)?st->counter:test->result_entries;    for(c = 0 ; c < max ; c++) {        calculated_number v = unpack_storage_number(rd->values[c]);        calculated_number n = test->results[c];        int same = (roundl(v * 10000000.0) == roundl(n * 10000000.0))?1:0;        fprintf(stderr, "    %s/%s: checking position %lu (at %lu secs), expecting value " CALCULATED_NUMBER_FORMAT ", found " CALCULATED_NUMBER_FORMAT ", %s/n",            test->name, rd->name, c+1,            (rrdset_first_entry_t(st) + c * st->update_every) - time_start,            n, v, (same)?"OK":"### E R R O R ###");        if(!same) errors++;        if(rd2) {            v = unpack_storage_number(rd2->values[c]);            n = test->results2[c];            same = (roundl(v * 10000000.0) == roundl(n * 10000000.0))?1:0;            fprintf(stderr, "    %s/%s: checking position %lu (at %lu secs), expecting value " CALCULATED_NUMBER_FORMAT ", found " CALCULATED_NUMBER_FORMAT ", %s/n",                test->name, rd2->name, c+1,                (rrdset_first_entry_t(st) + c * st->update_every) - time_start,                n, v, (same)?"OK":"### E R R O R ###");            if(!same) errors++;        }    }    return errors;}
开发者ID:acecommerce,项目名称:netdata,代码行数:94,


示例30: bind_to_one

static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {    int added = 0;    struct addrinfo hints;    struct addrinfo *result, *rp;    char buffer[strlen(definition) + 1];    strcpy(buffer, definition);    char buffer2[10 + 1];    snprintfz(buffer2, 10, "%d", default_port);    char *ip = buffer, *port = buffer2;    char *e = ip;    if(*e == '[') {        e = ++ip;        while(*e && *e != ']') e++;        if(*e == ']') {            *e = '/0';            e++;        }    }    else {        while(*e && *e != ':') e++;    }    if(*e == ':') {        port = e + 1;        *e = '/0';    }    if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))        ip = NULL;    if(!*port)        port = buffer2;    memset(&hints, 0, sizeof(struct addrinfo));    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */    hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */    hints.ai_protocol = 0;          /* Any protocol */    hints.ai_canonname = NULL;    hints.ai_addr = NULL;    hints.ai_next = NULL;    int r = getaddrinfo(ip, port, &hints, &result);    if (r != 0) {        error("getaddrinfo('%s', '%s'): %s/n", ip, port, gai_strerror(r));        return -1;    }    for (rp = result; rp != NULL; rp = rp->ai_next) {        int fd = -1;        char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";        int rport = default_port;        switch (rp->ai_addr->sa_family) {            case AF_INET: {                struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;                inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);                rport = ntohs(sin->sin_port);                fd = create_listen_socket4(rip, rport, listen_backlog);                break;            }            case AF_INET6: {                struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;                inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);                rport = ntohs(sin6->sin6_port);                fd = create_listen_socket6(rip, rport, listen_backlog);                break;            }        }        if (fd == -1)            error("Cannot bind to ip '%s', port %d", rip, default_port);        else {            add_listen_socket(fd, rip, rport);            added++;        }    }    return added;}
开发者ID:4224657,项目名称:netdata,代码行数:85,



注:本文中的snprintfz函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ snrm2_函数代码示例
C++ snprintf_P函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。