• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ LogInfo函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: LogError


//.........这里部分代码省略.........
			LogError("Invalid PCK resource string: \"%s\"", path.c_str());
			return nullptr;
		}
		auto imageSet =
		    this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]);
		if (!imageSet)
		{
			return nullptr;
		}
		// PCK resources come in the format:
		//"PCK:PCKFILE:TABFILE:INDEX"
		// or
		//"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space
		switch (splitString.size())
		{
			case 4:
			{
				img = imageSet->images[Strings::ToInteger(splitString[3])];
				break;
			}
			case 5:
			{
				std::shared_ptr<PaletteImage> pImg =
				    std::dynamic_pointer_cast<PaletteImage>(this->load_image(
				        "PCK:" + splitString[1] + ":" + splitString[2] + ":" + splitString[3]));
				assert(pImg);
				auto pal = this->load_palette(splitString[4]);
				assert(pal);
				img = pImg->toRGBImage(pal);
				break;
			}
			default:
				LogError("Invalid PCK resource string \"%s\"", path.c_str());
				return nullptr;
		}
	}
	else if (path.substr(0, 9) == "PCKSTRAT:")
	{
		auto splitString = path.split(':');
		if (splitString.size() != 3 && splitString.size() != 4 && splitString.size() != 5)
		{
			LogError("Invalid PCKSTRAT resource string: \"%s\"", path.c_str());
			return nullptr;
		}
		auto imageSet =
		    this->load_image_set(splitString[0] + ":" + splitString[1] + ":" + splitString[2]);
		if (!imageSet)
		{
			return nullptr;
		}
		// PCK resources come in the format:
		//"PCK:PCKFILE:TABFILE:INDEX"
		// or
		//"PCK:PCKFILE:TABFILE:INDEX:PALETTE" if we want them already in rgb space
		switch (splitString.size())
		{
			case 4:
			{
				img = imageSet->images[Strings::ToInteger(splitString[3])];
				break;
			}
			case 5:
			{
				std::shared_ptr<PaletteImage> pImg = std::dynamic_pointer_cast<PaletteImage>(
				    this->load_image("PCKSTRAT:" + splitString[1] + ":" + splitString[2] + ":" +
				                     splitString[3]));
				assert(pImg);
				auto pal = this->load_palette(splitString[4]);
				assert(pal);
				img = pImg->toRGBImage(pal);
				break;
			}
			default:
				LogError("Invalid PCKSTRAT resource string \"%s\"", path.c_str());
				return nullptr;
		}
	}
	else
	{
		for (auto &loader : imageLoaders)
		{
			img = loader->loadImage(GetCorrectCaseFilename(path));
			if (img)
			{
				break;
			}
		}
		if (!img)
		{
			LogInfo("Failed to load image \"%s\"", path.c_str());
			return nullptr;
		}
	}

	this->pinnedImages.push(img);
	this->pinnedImages.pop();

	this->imageCache[cacheKey] = img;
	return img;
}
开发者ID:aglenday,项目名称:OpenApoc,代码行数:101,代码来源:data.cpp


示例2: FilterRestart


//.........这里部分代码省略.........
    }

    // Iterate and process returned capabilities
    while (SpinelCapsLen > 0)
    {
        ULONG SpinelCap = 0;
        spinel_ssize_t len = spinel_datatype_unpack(SpinelCapsPtr, SpinelCapsLen, SPINEL_DATATYPE_UINT_PACKED_S, &SpinelCap);
        if (len < 1) break;
        SpinelCapsLen -= (spinel_size_t)len;

        switch (SpinelCap)
        {
        case SPINEL_CAP_MAC_RAW:
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO;
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO_ACK_TIMEOUT;
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_RADIO_ENERGY_SCAN;
            break;
        case SPINEL_CAP_NET_THREAD_1_0:
            pFilter->DeviceCapabilities |= OTLWF_DEVICE_CAP_THREAD_1_0;
            break;
        default:
            break;
        }
    }

    // Set the state indicating where we should be running the Thread logic (Host or Device).
    if (!NT_SUCCESS(GetRegDWORDValue(pFilter, L"RunOnHost", &ThreadOnHost)))
    {
        // Default to running on the host if the key isn't present
        ThreadOnHost = TRUE;
        SetRegDWORDValue(pFilter, L"RunOnHost", ThreadOnHost);
    }

    LogInfo(DRIVER_DEFAULT, "Filter: %p initializing ThreadOnHost=%d", FilterModuleContext, ThreadOnHost);

    // Initialize the processing logic
    if (ThreadOnHost)
    {
        // Ensure the device has the capabilities to support raw radio commands
        if ((pFilter->DeviceCapabilities & OTLWF_DEVICE_CAP_RADIO) == 0)
        {
            LogError(DRIVER_DEFAULT, "Failed to start because device doesn't support raw radio commands");
            NdisStatus = NDIS_STATUS_NOT_SUPPORTED;
            goto exit;
        }

        pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_RADIO_MODE;
        NtStatus = otLwfInitializeThreadMode(pFilter);
        if (!NT_SUCCESS(NtStatus))
        {
            LogError(DRIVER_DEFAULT, "otLwfInitializeThreadMode failed, %!STATUS!", NtStatus);
            NdisStatus = NDIS_STATUS_FAILURE;
            pFilter->DeviceStatus = OTLWF_DEVICE_STATUS_UNINTIALIZED;
            goto exit;
        }
    }
    else
    {
        // Ensure the device has the capabilities to support Thread commands
        if ((pFilter->DeviceCapabilities & OTLWF_DEVICE_CAP_THREAD_1_0) == 0)
        {
            LogError(DRIVER_DEFAULT, "Failed to start because device doesn't support thread commands");
            NdisStatus = NDIS_STATUS_NOT_SUPPORTED;
            goto exit;
        }
开发者ID:HarryMorris,项目名称:openthread,代码行数:66,代码来源:filter.c


示例3: SetNameFunction

/**
 * _9p_dispatcher_thread: thread used for RPC dispatching.
 *
 * This function is the main loop for the 9p dispatcher.
 * It never returns because it is an infinite loop.
 *
 * @param Arg (unused)
 *
 * @return Pointer to the result (but this function will mostly loop forever).
 *
 */
void *_9p_dispatcher_thread(void *Arg)
{
	int _9p_socket;
	int rc = 0;
	long int newsock = -1;
	pthread_attr_t attr_thr;
	pthread_t tcp_thrid;

	SetNameFunction("_9p_disp");

	/* Calling dispatcher main loop */
	LogInfo(COMPONENT_9P_DISPATCH, "Entering nfs/rpc dispatcher");

	LogDebug(COMPONENT_9P_DISPATCH, "My pthread id is %p",
		 (caddr_t) pthread_self());

	/* Set up the _9p_socket (trying V6 first, will fall back to V4
	 * if V6 fails).
	 */
	_9p_socket = _9p_create_socket_V6();

	if (_9p_socket == -1) {
		LogFatal(COMPONENT_9P_DISPATCH,
			 "Can't get socket for 9p dispatcher");
	}

	/* Init for thread parameter (mostly for scheduling) */
	if (pthread_attr_init(&attr_thr) != 0)
		LogDebug(COMPONENT_9P_DISPATCH,
			 "can't init pthread's attributes");

	if (pthread_attr_setscope(&attr_thr, PTHREAD_SCOPE_SYSTEM) != 0)
		LogDebug(COMPONENT_9P_DISPATCH, "can't set pthread's scope");

	if (pthread_attr_setdetachstate(&attr_thr,
					PTHREAD_CREATE_DETACHED) != 0)
		LogDebug(COMPONENT_9P_DISPATCH,
			 "can't set pthread's join state");

	LogEvent(COMPONENT_9P_DISPATCH, "9P dispatcher started");

	while (true) {
		newsock = accept(_9p_socket, NULL, NULL);

		if (newsock < 0) {
			LogCrit(COMPONENT_9P_DISPATCH, "accept failed: %d",
				errno);
			continue;
		}

		/* Starting the thread dedicated to signal handling */
		rc = pthread_create(&tcp_thrid, &attr_thr,
				    _9p_socket_thread, (void *)newsock);
		if (rc != 0) {
			LogFatal(COMPONENT_THREAD,
				 "Could not create 9p socket manager thread, error = %d (%s)",
				 errno, strerror(errno));
		}
	}			/* while */

	close(_9p_socket);

	return NULL;
}				/* _9p_dispatcher_thread */
开发者ID:Anuradha-Talur,项目名称:nfs-ganesha,代码行数:75,代码来源:9p_dispatcher.c


示例4: printReceiveStatistics

static void printReceiveStatistics(LONGHAUL_RECEIVE_STATISTICS* stats)
{
	LogInfo("Number of Messages: Sent=%lu, Received=%lu; Travel Time (secs): Min=%f, Max=%f, Average=%f",
		stats->numberOfMessagesReceivedByClient, stats->numberOfMessagesReceivedByClient, stats->minMessageTravelTime, stats->maxMessageTravelTime, stats->avgMessageTravelTime);
}
开发者ID:DemofiloVizuete,项目名称:azure-iot-sdks,代码行数:5,代码来源:longhaul_tests.cpp


示例5: sendEventLoop

static int sendEventLoop(IOTHUB_CLIENT_HANDLE iotHubClientHandle, LONGHAUL_SEND_TEST_STATE* test_state)
{
	int result = 0;

#ifndef MBED_BUILD_TIMESTAMP
	IOTHUB_TEST_HANDLE iotHubTestHandle;

	if ((iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo), IoTHubAccount_GetDeviceId(g_iothubAcctInfo), IoTHubAccount_GetDeviceKey(g_iothubAcctInfo), IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo))) == NULL)
	{
		LogError("Failed initializing the Event Hub test client.");
		result = __LINE__;
	}
	else
	{
		initializeSendStatistics(&test_state->statistics);
#endif
		time_t testInitialTime;

		if ((testInitialTime = time(NULL)) == INDEFINITE_TIME)
		{
			LogError("Failed setting the initial time of the test (time(NULL) failed).");
			result = __LINE__;
		}
		else
		{
			time_t loopIterationStartTimeInSeconds, loopIterationEndTimeInSeconds;
			double loopIterationTotalTime;
			time_t testCurrentTime;

			while (result == 0)
			{
				if ((testCurrentTime = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the current time of the test (time(NULL) failed)");
					result = __LINE__;
					break;
				}
				else if (difftime(testCurrentTime, testInitialTime) > test_state->profile->totalRunTimeInSeconds)
				{
					LogInfo("Test run for the expected duration (%d seconds)", test_state->profile->totalRunTimeInSeconds);
					break;
				}

				if ((loopIterationStartTimeInSeconds = time(NULL)) == INDEFINITE_TIME)
				{
					LogError("Failed setting the initial time of the send/receive loop (time(NULL) failed)");
					result = __LINE__;
					break;
				}

				if (test_state->timeUntilNextSendEventInSeconds <= 0.0)
				{
					EXPECTED_SEND_DATA* sendData;
					IOTHUB_MESSAGE_HANDLE msgHandle;

					if ((sendData = EventData_Create()) == NULL)
					{
						LogError("Failed creating EXPECTED_SEND_DATA.");
						result = __LINE__;
					}
					else
					{
						if ((msgHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)sendData->expectedString, strlen(sendData->expectedString))) == NULL)
						{
							LogError("Failed creating IOTHUB_MESSAGE_HANDLE.");
							result = __LINE__;
						}
						else
						{
							if (IoTHubClient_SendEventAsync(iotHubClientHandle, msgHandle, SendConfirmationCallback, sendData) != IOTHUB_CLIENT_OK)
							{
								LogError("Call to IoTHubClient_SendEventAsync failed.");
								result = __LINE__;
							}
							else
							{
								bool dataWasSent = false;
								time_t beginOperation, nowTime;

								if ((beginOperation = time(NULL)) == INDEFINITE_TIME)
								{
									LogError("Failed setting beginOperation (time(NULL) failed).");
									result = __LINE__;
								}
								else
								{
									do
									{
										if (Lock(sendData->lock) != LOCK_OK)
										{
											LogError("Unable to lock to flag event sent.");
											break;
										}
										else
										{
											if (sendData->dataWasSent)
											{
												dataWasSent = true;
												Unlock(sendData->lock);
												break;
//.........这里部分代码省略.........
开发者ID:DemofiloVizuete,项目名称:azure-iot-sdks,代码行数:101,代码来源:longhaul_tests.cpp


示例6: conf_file_init

TSS_RESULT
conf_file_init(struct tcsd_config *conf)
{
	FILE *f = NULL;
	struct stat stat_buf;
#ifndef SOLARIS
	struct group *grp;
	struct passwd *pw;
	mode_t mode = (S_IRUSR|S_IWUSR);
#endif /* SOLARIS */
	TSS_RESULT result;

	init_tcsd_config(conf);

#ifdef SOLARIS
       /*
	* Solaris runs as root:sys but with reduced privileges
	* so we don't need to create a new user/group and also so
	* we can have auditing support.  The permissions on
	* the tcsd configuration file are not checked on Solaris.
	*/
#endif
	/* look for a config file, create if it doesn't exist */
	if (stat(TCSD_CONFIG_FILE, &stat_buf) == -1) {
		if (errno == ENOENT) {
			/* no config file? use defaults */
			config_set_defaults(conf);
			LogInfo("Config file %s not found, using defaults.", TCSD_CONFIG_FILE);
			return TSS_SUCCESS;
		} else {
			LogError("stat(%s): %s", TCSD_CONFIG_FILE, strerror(errno));
			return TCSERR(TSS_E_INTERNAL_ERROR);
		}
	}

#ifndef SOLARIS
	/* find the gid that owns the conf file */
	errno = 0;
	grp = getgrnam(TSS_GROUP_NAME);
	if (grp == NULL) {
		if (errno == 0) {
			LogError("Group \"%s\" not found, please add this group"
					" manually.", TSS_GROUP_NAME);
		} else {
			LogError("getgrnam(%s): %s", TSS_GROUP_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	errno = 0;
	pw = getpwnam(TSS_USER_NAME);
	if (pw == NULL) {
		if (errno == 0) {
			LogError("User \"%s\" not found, please add this user"
					" manually.", TSS_USER_NAME);
		} else {
			LogError("getpwnam(%s): %s", TSS_USER_NAME, strerror(errno));
		}
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure user/group TSS owns the conf file */
	if (pw->pw_uid != stat_buf.st_uid || grp->gr_gid != stat_buf.st_gid) {
		LogError("TCSD config file (%s) must be user/group %s/%s", TCSD_CONFIG_FILE,
				TSS_USER_NAME, TSS_GROUP_NAME);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	/* make sure only the tss user can manipulate the config file */
	if (((stat_buf.st_mode & 0777) ^ mode) != 0) {
		LogError("TCSD config file (%s) must be mode 0600", TCSD_CONFIG_FILE);
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}
#endif /* SOLARIS */

	if ((f = fopen(TCSD_CONFIG_FILE, "r")) == NULL) {
		LogError("fopen(%s): %s", TCSD_CONFIG_FILE, strerror(errno));
		return TCSERR(TSS_E_INTERNAL_ERROR);
	}

	result = read_conf_file(f, conf);
	fclose(f);

	/* fill out any uninitialized options */
	config_set_defaults(conf);

#ifdef SOLARIS
	/*
	* The SMF value for "local_only" overrides the config file and
	* disables all remote operations.
	*/
if (get_smf_prop("local_only", B_TRUE)) {
		(void) memset(conf->remote_ops, 0, sizeof(conf->remote_ops));
		conf->unset |= TCSD_OPTION_REMOTE_OPS;
	
	}
#endif
	return result;
}
开发者ID:wy461132,项目名称:repository,代码行数:99,代码来源:tcsd_conf.c


示例7: Print_param_worker_in_log

/**
 *
 * Print_param_in_log : prints the nfs worker parameter structure into the logfile
 *
 * prints the nfs worker parameter structure into the logfile
 *
 * @param pparam Pointer to the nfs worker parameter
 *
 * @return none (void function)
 *
 */
void Print_param_worker_in_log(nfs_worker_parameter_t * pparam)
{
  LogInfo(COMPONENT_INIT,
          "NFS PARAM : worker_param.nb_before_gc = %d",
          pparam->nb_before_gc);
}                               /* Print_param_worker_in_log */
开发者ID:fmarsch,项目名称:nfs-ganesha-1,代码行数:17,代码来源:nfs_read_conf.c


示例8: in

Launch::Launch()
{
	successfullRead = GL_FALSE;

	std::string nameOfFile = "launch";

	// Read XML from file
	std::ifstream in(std::string(nameOfFile + ".xml").c_str());

	// Check whether file exisits
	if(!in.is_open())
	{
		LogWarning("'launch.xml' was not found!");
		createNewLaunchFile();
		LogInfo("New 'launch.xml' was created! 'None' warnings will follow ;)");
		in.open(std::string(nameOfFile + ".xml").c_str());
	}

	// File exisits, lets hope the best
	std::stringstream buffer;
	buffer << in.rdbuf();
	in.close();
	std::string content(buffer.str());
	std::vector<GLchar> xml(content.begin(), content.end());
    xml.push_back('\0');

	// Parse it to a doc
	rapidxml::xml_document<> doc;
	doc.parse<rapidxml::parse_declaration_node | rapidxml::parse_no_data_nodes>(&xml[0]);

	// Launch (jump over declaration)
	rapidxml::xml_node<>* pRootNode = doc.first_node()->next_sibling();
	checkValue(std::string(pRootNode->name()), "launch", nameOfFile);

	// Get Version
	rapidxml::xml_attribute<>* pRootNodeCurrentAttribute = pRootNode->first_attribute();
	checkValue(std::string(pRootNodeCurrentAttribute->name()), "version", nameOfFile);
	GLfloat version = convertCharToFloat(pRootNodeCurrentAttribute->value());

	// Preparation of reading
	rapidxml::xml_node<>* pChildNode;
	rapidxml::xml_attribute<>* pNodeCurrentAttribute;
	GLuint errorCounter = 0;

	// Window width
	pChildNode = pRootNode->first_node();
	errorCounter += checkValue(std::string(pChildNode->name()), "windowWidth", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	windowWidth = static_cast<GLuint>(convertCharToFloat(pNodeCurrentAttribute->value()));

	// Window height
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "windowHeight", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	windowHeight = static_cast<GLuint>(convertCharToFloat(pNodeCurrentAttribute->value()));

	// Fullscreen
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "fullscreen", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	fullscreen = convertCharToBool(pNodeCurrentAttribute->value());

	// Volume
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "volume", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	volume = convertCharToString(pNodeCurrentAttribute->value());

	// Transferfunction
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "transferfunction", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	transferfunction = convertCharToString(pNodeCurrentAttribute->value());

	// Raycaster
	pChildNode = pChildNode->next_sibling();
	errorCounter += checkValue(std::string(pChildNode->name()), "raycaster", nameOfFile);
	pNodeCurrentAttribute = pChildNode->first_attribute();
	errorCounter += checkValue(std::string(pNodeCurrentAttribute->name()), "value", nameOfFile);
	raycaster = convertCharToString(pNodeCurrentAttribute->value());

	// Check whether everything was read successfully
	successfullRead = (errorCounter == 0);
}
开发者ID:raphaelmenges,项目名称:Voraca,代码行数:89,代码来源:Launch.cpp


示例9: Multicast_receive_socket

int Multicast_receive_socket (const char *hostname, const char *listenport, int family, int sockbuflen)
{
	struct addrinfo hints, *res, *ressave;
	socklen_t optlen;
	int p, error, sockfd;

	if (!listenport) {
		fprintf (stderr, "listen port required!\n");
		LogError ("listen port required!");
		return -1;
	}

	memset (&hints, 0, sizeof (struct addrinfo));
	hints.ai_family = family;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo (hostname, listenport, &hints, &res);

	if (error) {
		fprintf (stderr, "getaddrinfo error:: [%s]\n", gai_strerror (error));
		LogError ("getaddrinfo error:: [%s]", gai_strerror (error));
		return -1;
	}


	/*
	   Try open socket with each address getaddrinfo returned,
	   until we get a valid listening socket.
	*/

	sockfd = -1;
	ressave = res;
	while (res) {
		sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
		if (sockfd < 0) {
			res = res->ai_next;
			continue;
		}

		// we found a valid socket and are done in this loop
		break;
	}

	if (sockfd < 0) {
		// nothing found - bye bye
		fprintf (stderr, "Could not create a socket for [%s:%s]\n", hostname, listenport);
		LogError ("Could not create a socket for [%s:%s]", hostname, listenport);
		freeaddrinfo (ressave);
		return -1;
	}


	if (isMulticast ( (struct sockaddr_storage *) res->ai_addr) < 0) {
		fprintf (stderr, "Not a multicast address [%s]\n", hostname);
		LogError ("Not a multicast address [%s]", hostname);
		freeaddrinfo (ressave);
		return -1;
	}

	close (sockfd);


	sockfd = socket (res->ai_family, SOCK_DGRAM, 0);
	if (bind (sockfd, res->ai_addr, res->ai_addrlen) < 0) {
		fprintf (stderr, "bind: %s\n", strerror (errno));
		LogError ("bind: %s", strerror (errno));
		close (sockfd);
		freeaddrinfo (ressave);
		return -1;
	}

	if (joinGroup (sockfd, 1 , 1, (struct sockaddr_storage *) res->ai_addr) < 0) {
		close (sockfd);
		freeaddrinfo (ressave);
		return -1;
	}

	if (res->ai_family == AF_INET)
		LogInfo ("Joined IPv4 multicast group: %s Port: %s", hostname, listenport);
	if (res->ai_family == AF_INET6)
		LogInfo ("Joined IPv6 multicat group: %s Port: %s", hostname, listenport);


	freeaddrinfo (ressave);

	if (sockbuflen) {
		if (sockbuflen < Min_SOCKBUFF_LEN) {
			sockbuflen = Min_SOCKBUFF_LEN;
			LogInfo ("I want at least %i bytes as socket buffer", sockbuflen);
		}
		optlen = sizeof (p);
		getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
		LogInfo ("Standard setsockopt, SO_RCVBUF is %i Requested length is %i bytes", p, sockbuflen);
		if ( (setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &sockbuflen, sizeof (sockbuflen)) != 0)) {
			fprintf (stderr, "setsockopt(SO_RCVBUF,%d): %s\n", sockbuflen, strerror (errno));
			LogError ("setsockopt(SO_RCVBUF,%d): %s", sockbuflen, strerror (errno));
			close (sockfd);
			return -1;
		} else {
			getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
//.........这里部分代码省略.........
开发者ID:exaexa,项目名称:nfdump,代码行数:101,代码来源:nfnet.c


示例10: printf

bool Controller::Initialize(const char* server_name, const char* configure_file)
{
    _server_name = server_name;
    _configure_file = configure_file;

    // 加载配置
    if (!gConfigureMap.Load(configure_file))
    {
        printf("error: %s\n", gConfigureMap.GetErrMsg().c_str());
        return false;
    }
    gConfigureMap.Print();

    // 初始化日志
    std::string log_path = JoinPath(gConfigureMap["log"]["log_path"].str(), server_name);
    if (!Logger::Initialize(log_path.c_str(),
                           gConfigureMap["log"]["max_file_size"].as<uint32_t>(DefaultConf::kMaxLogFileSize),
                           gConfigureMap["log"]["max_file_num"].as<uint32_t>(DefaultConf::kMaxLogFileNum),
                           gConfigureMap["log"]["log_level"].c_str())) {
        printf("logger initialize failed, errmsg: %s\n", Logger::GetErrMsg().c_str());
    }

    LogInfo("Logger initialize succeed\n");

    int poller_max_event = gConfigureMap["poller_max_event"].as<int>(DefaultConf::kPollerMaxEventNum);
    assert(poller_max_event > 0);
    _poller = new Poller(poller_max_event);
    assert(_poller);

    LogInfo("Poller initialize succeed\n");

    // 初始化监听端口

    // TODO different port bind different protocol(unpack function)
    // 每个监听端口最好能独立的包完整性检查,每个访问外部server的端口,最好也能绑定独立协议
    const Value & val = gConfigureMap["listen"];
    _listen_size = val.size() + 128;
    _listen_sockets = new ListenFdInfo[_listen_size];
    for (uint32_t i=0; i<_listen_size; ++i)
    {
        unsigned int port = val[i]["port"].as<unsigned>(0);
        int fd = ListenTcpV4(port);
        if (fd < 0) {
            FillErrmsg("listen failed: ", errno);
            return false;
        }

        _listen_sockets[fd].port = port;
        _listen_sockets[fd].fd = fd;

        if (_poller->Add(fd, (uint64_t)fd, EPOLLIN)) {
            FillErrmsg("listen fd add to poller failed: ", errno);
            return false;
        }
    }

    _io_handler_num = gConfigureMap["server"]["io_handler_num"].as<uint32_t>(DefaultConf::kIoHandlerNum);
    _io_handers = new IoHandler[_io_handler_num];
    assert(_io_handers);
    for (uint32_t i=0; i<_io_handler_num; ++i) {
        if(!_io_handers[i].Initialize()) {
            _errmsg = "io handler initialize failed";
            return false;
        }
    }

    _worker_num = gConfigureMap["server"]["worker_num"].as<uint32_t>(DefaultConf::kWorkerNum);
    _workers = new Worker[_worker_num];
    assert(_workers);
    for (uint32_t i=0; i<_worker_num; ++i) {
        if(!_workers[i].Initialize()) {
            _errmsg = "initialize workers failed";
            return false;
        }
    }

    int pool_size = _io_handler_num + _worker_num;
    int queue_size = gConfigureMap["server"]["queue_size"].as<uint32_t>(DefaultConf::kQueueSize);
    _task_pool = new TaskPool();
    assert(_task_pool);
    if (!_task_pool->Initialize(pool_size, queue_size)) {
        LogErr("task poll initialize failed");
        return false;
    }

    return true;
}
开发者ID:keynumber,项目名称:ef,代码行数:87,代码来源:controller.cpp


示例11: SplitStringToMap

//校验请求是否正确
int CLogin4399::check_login(const char* plat_name, const char* pszReq, string& strAccountGot)
{  	
// 	if ( m_str_plat_name !=  (string)plat_name)
// 	{
// 		LogWarning("check_login", "plat :%s != %s", plat_name, m_str_plat_name.c_str());
// 		return ENUM_LOGIN_PLAT_NAME_ERROR;
// 	}

	//port=123&suid=xxx&timestamp=12345&sign=xxx&platid=111&plataccount=xxx&token=xxx

	//解析登录是否合法
	map<string, string> dictParams;
	SplitStringToMap(pszReq, '&', '=', dictParams);

	//校验客户端发来的loginapp端口是否在合法
	//uLoginappPort = (uint16_t)atoi(get_dict_field(dictParams, "port").c_str());
	//if(uLoginappPort < LOGINAPP_MIN_PORT || uLoginappPort > LOGINAPP_MAX_PORT)
	//{
	//    LogError("login_porterr", "req=%s", pszReq);
	//    return ENUM_LOGIN_INNER_ERR;
	//}
	//loginapp端口改为读配置
	//uint16_t unPortFromClient = (uint16_t)atoi(get_dict_field(dictParams, "port").c_str());

	//平台的时间戳
	const string&  strTime = get_dict_field(dictParams, "timestamp");	
	int nTimestamp = atoi(strTime.c_str());
	int nTimeNow = time(NULL);
	//比服务器时间滞后超过20分钟,或者超前多于5分钟算时间无效
	if(nTimeNow > nTimestamp + 1200 || nTimestamp > nTimeNow + 300)
	{
		LogError("login_timeout", "req=%s", pszReq);
		return ENUM_LOGIN_TIME_ILLEGAL;		
	}

	const string& strSuid = get_dict_field(dictParams, "suid");
	const string& strSign = get_dict_field(dictParams, "sign");
	//检查md5是否匹配
	//flag=md5("$suid&$timestamp&%key")
	{
		std::ostringstream oss;
		oss << strSuid << '&' << strTime << '&' << this->get_cfg_value("key", sg_szLoginKey);		
		const string& strOss = oss.str();
		
		string __md5 = getmd5(strOss);		

		if(strcasecmp(__md5.c_str(), strSign.c_str()) != 0 )
		{
			//md5签名不匹配,错误的请求
			return ENUM_LOGIN_SIGN_ILLEGAL;
		}
	}

	//到平台验证tocken是否正确
	const string& strTocken = get_dict_field(dictParams, "tocken");
	const string& strAccount = get_dict_field(dictParams, "plataccount");
	{
		string resp = "";
		string strUrl = this->get_cfg_value("url", sg_szVerifyUrl).append(strTocken);
		int ret = GetUrl_new(strUrl.c_str(), resp);
		if (ret != CURLE_OK)
		{
			LogWarning("login_urlerr", "ret=%d;req=%s", ret, pszReq);
			return ENUM_LOGIN_SERVER_BUSY;
		}
		Trim(resp);


		JsonHelper jsonhp(resp);

		int rst = 0;
		if (!jsonhp.GetJsonItem("code", rst))
		{
			//平台返回字符串解析失败
			LogWarning("login_jsonfailed", "json=%s", resp.c_str());
			return ENUM_LOGIN_SDK_VERIFY_FAILED;
		}

		if (rst != 1)
		{
			//结果码为1表示验证成功,其他值都是失败
			LogWarning("login_verifyfailed", "rst=%d;req=%s", rst, pszReq);
			return ENUM_LOGIN_SDK_VERIFY_FAILED;            
		}
	}

	//需要返回的参数值
	strAccountGot.assign(strSuid);

	LogInfo("login_req", "%s", pszReq);
	return ENUM_LOGIN_SUCCESS;
}
开发者ID:1suming,项目名称:bigworld_ahzs,代码行数:93,代码来源:login4399.cpp


示例12: ethernet_init

bool ethernet_init(
    char *if_name)
{
    PPACKET_OID_DATA pOidData;
    LPADAPTER lpAdapter;
    pcap_if_t *pcap_all_if;
    pcap_if_t *dev;
    BOOLEAN result;
    CHAR str[sizeof(PACKET_OID_DATA) + 128];
    int i;
    char msgBuf[200];

    if (ethernet_valid())
        ethernet_cleanup();

    /**
     * Find the interface user specified
     */
    /* Retrieve the device list */
    if (pcap_findalldevs(&pcap_all_if, pcap_errbuf) == -1) {
        sprintf(msgBuf, "ethernet.c: error in pcap_findalldevs: %s\n",
            pcap_errbuf);
        LogError(msgBuf);
        return false;
    }
    /* Scan the list printing every entry */
    for (dev = pcap_all_if; dev; dev = dev->next) {
        if (strcmp(if_name, dev->name) == 0)
            break;
    }
    pcap_freealldevs(pcap_all_if);      /* we don't need it anymore */
    if (dev == NULL) {
        sprintf(msgBuf, "ethernet.c: specified interface not found: %s\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    /**
     * Get local MAC address
     */
    ZeroMemory(str, sizeof(PACKET_OID_DATA) + 128);
    lpAdapter = PacketOpenAdapter(if_name);
    if (lpAdapter == NULL) {
        ethernet_cleanup();
        sprintf(msgBuf, "ethernet.c: error in PacketOpenAdapter(\"%s\")\n",
            if_name);
        LogError(msgBuf);
        return false;
    }
    pOidData = (PPACKET_OID_DATA) str;
    pOidData->Oid = OID_802_3_CURRENT_ADDRESS;
    pOidData->Length = 6;
    result = PacketRequest(lpAdapter, FALSE, pOidData);
    if (!result) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        LogError("ethernet.c: error in PacketRequest()\n");
        return false;
    }
    for (i = 0; i < 6; ++i)
        Ethernet_MAC_Address[i] = pOidData->Data[i];
    PacketCloseAdapter(lpAdapter);

    /**
     * Open interface for subsequent sending and receiving
     */
    /* Open the output device */
    pcap_eth802_fp = pcap_open(if_name, /* name of the device */
        MAX_MPDU,       /* portion of the packet to capture */
        PCAP_OPENFLAG_PROMISCUOUS,      /* promiscuous mode */
        eth_timeout,    /* read timeout */
        NULL,   /* authentication on the remote machine */
        pcap_errbuf     /* error buffer */
        );
    if (pcap_eth802_fp == NULL) {
        PacketCloseAdapter(lpAdapter);
        ethernet_cleanup();
        sprintf(msgBuf,
            "ethernet.c: unable to open the adapter. %s is not supported by WinPcap\n",
            if_name);
        LogError(msgBuf);
        return false;
    }

    LogInfo("ethernet.c: ethernet_init() ok.\n");

    atexit(ethernet_cleanup);

    return ethernet_valid();
}
开发者ID:HITliuyu,项目名称:NES15_HEVC,代码行数:91,代码来源:ethernet.c


示例13: main


//.........这里部分代码省略.........
	}

	if ( do_daemonize && !InitLog(argv[0], SYSLOG_FACILITY)) {
		exit(255);
	}

	InitExtensionMaps(NO_EXTENSION_LIST);
	SetupExtensionDescriptors(strdup(extension_tags));

	// Debug code to read from pcap file
#ifdef PCAP
	sock = 0;
	if ( pcap_file ) {
		printf("Setup pcap reader\n");
		setup_packethandler(pcap_file, NULL);
		receive_packet 	= NextPacket;
	} else 
#endif
	if ( mcastgroup ) 
		sock = Multicast_receive_socket (mcastgroup, listenport, family, bufflen);
	else 
		sock = Unicast_receive_socket(bindhost, listenport, family, bufflen );

	if ( sock == -1 ) {
		fprintf(stderr,"Terminated due to errors.\n");
		exit(255);
	}

	if ( peer.hostname ) {
		peer.sockfd = Unicast_send_socket (peer.hostname, peer.port, peer.family, bufflen, 
											&peer.addr, &peer.addrlen );
		if ( peer.sockfd <= 0 )
			exit(255);
		LogInfo("Replay flows to host: %s port: %s", peer.hostname, peer.port);
	}

	if ( sampling_rate < 0 ) {
		default_sampling = -sampling_rate;
		overwrite_sampling = default_sampling;
	} else {
		default_sampling = sampling_rate;
	}

	SetPriv(userid, groupid);

	if ( subdir_index && !InitHierPath(subdir_index) ) {
		close(sock);
		exit(255);
	}

	// check if pid file exists and if so, if a process with registered pid is running
	if ( strlen(pidfile) ) {
		int pidf;
		pidf = open(pidfile, O_RDONLY, 0);
		if ( pidf > 0 ) {
			// pid file exists
			char s[32];
			ssize_t len;
			len = read(pidf, (void *)s, 31);
			close(pidf);
			s[31] = '\0';
			if ( len < 0 ) {
				fprintf(stderr, "read() error existing pid file: %s\n", strerror(errno));
				exit(255);
			} else {
				unsigned long pid = atol(s);
开发者ID:saiganji,项目名称:oni-nfdump,代码行数:67,代码来源:nfcapd.c


示例14: run


//.........这里部分代码省略.........
				// Flush Exporter Stat to file
				FlushExporterStats(fs);
				// Close file
				CloseUpdateFile(nffile, fs->Ident);

				if ( subdir && !SetupSubDir(fs->datadir, subdir, error, 255) ) {
					// in this case the flows get lost! - the rename will fail
					// but this should not happen anyway, unless i/o problems, inode problems etc.
					LogError("Ident: %s, Failed to create sub hier directories: %s", fs->Ident, error );
				}

				// if rename fails, we are in big trouble, as we need to get rid of the old .current file
				// otherwise, we will loose flows and can not continue collecting new flows
				err = rename(fs->current, nfcapd_filename);
				if ( err ) {
					LogError("Ident: %s, Can't rename dump file: %s", fs->Ident,  strerror(errno));
					LogError("Ident: %s, Serious Problem! Fix manually", fs->Ident);
					if ( launcher_pid )
						commbuff->failed = 1;

					// we do not update the books here, as the file failed to rename properly
					// otherwise the books may be wrong
				} else {
					struct stat	fstat;
					if ( launcher_pid )
						commbuff->failed = 0;

					// Update books
					stat(nfcapd_filename, &fstat);
					UpdateBooks(fs->bookkeeper, t_start, 512*fstat.st_blocks);
				}

				// log stats
				LogInfo("Ident: '%s' Flows: %llu, Packets: %llu, Bytes: %llu, Sequence Errors: %u, Bad Packets: %u", 
					fs->Ident, (unsigned long long)nffile->stat_record->numflows, (unsigned long long)nffile->stat_record->numpackets, 
					(unsigned long long)nffile->stat_record->numbytes, nffile->stat_record->sequence_failure, fs->bad_packets);

				// reset stats
				fs->bad_packets = 0;
				fs->first_seen  = 0xffffffffffffLL;
				fs->last_seen 	= 0;

				if ( !done ) {
					nffile = OpenNewFile(fs->current, nffile, compress, 0, NULL);
					if ( !nffile ) {
						LogError("killed due to fatal error: ident: %s", fs->Ident);
						break;
					}
					/* XXX needs fixing */
					if ( fs->xstat ) {
						// to be implemented
					}
				}

				// Dump all extension maps and exporters to the buffer
				FlushStdRecords(fs);

				// next flow source
				fs = fs->next;
			} // end of while (fs)

			// All flow sources updated - signal launcher if required
			if ( launcher_pid ) {
				// Signal launcher
		
				// prepare filename for %f expansion
开发者ID:saiganji,项目名称:oni-nfdump,代码行数:67,代码来源:nfcapd.c


示例15: doParallelSuperPMI


//.........这里部分代码省略.........
    }

    SpmiResult result = SpmiResult::Success;

    if (!closeRequested)
    {
        // Figure out the error code to use.
        // Mainly, if any child returns non-zero, we want to return non-zero, to indicate failure.
        for (int i = 0; i < o.workerCount; i++)
        {
            DWORD      exitCodeTmp;
            BOOL       ok          = GetExitCodeProcess(hProcesses[i], &exitCodeTmp);
            SpmiResult childResult = (SpmiResult)exitCodeTmp;
            if (ok && (childResult != result))
            {
                if (result == SpmiResult::Error || childResult == SpmiResult::Error)
                {
                    result = SpmiResult::Error;
                }
                else if (result == SpmiResult::Diffs || childResult == SpmiResult::Diffs)
                {
                    result = SpmiResult::Diffs;
                }
                else if (result == SpmiResult::Misses || childResult == SpmiResult::Misses)
                {
                    result = SpmiResult::Misses;
                }
                else if (result == SpmiResult::JitFailedToInit || childResult == SpmiResult::JitFailedToInit)
                {
                    result = SpmiResult::JitFailedToInit;
                }
                else
                {
                    result = SpmiResult::GeneralFailure;
                }
            }
        }

        bool usageError = false; // variable to flag if we hit a usage error in SuperPMI

        int loaded = 0, jitted = 0, failed = 0, excluded = 0, diffs = 0;

        // Read the stderr files and log them as errors
        // Read the stdout files and parse them for counts and log any MISSING or ISSUE errors
        for (int i = 0; i < o.workerCount; i++)
        {
            ProcessChildStdErr(arrStdErrorPath[i]);
            ProcessChildStdOut(o, arrStdOutputPath[i], &loaded, &jitted, &failed, &excluded, &diffs, &usageError);
            if (usageError)
                break;
        }

        if (o.mclFilename != nullptr && !usageError)
        {
            // Concat the resulting .mcl files
            MergeWorkerMCLs(o.mclFilename, arrFailingMCListPath, o.workerCount);
        }

        if (o.diffMCLFilename != nullptr && !usageError)
        {
            // Concat the resulting diff .mcl files
            MergeWorkerMCLs(o.diffMCLFilename, arrDiffMCListPath, o.workerCount);
        }

        if (!usageError)
        {
            if (o.applyDiff)
            {
                LogInfo(g_AsmDiffsSummaryFormatString, loaded, jitted, failed, excluded, diffs);
            }
            else
            {
                LogInfo(g_SummaryFormatString, loaded, jitted, failed, excluded);
            }
        }

        st.Stop();
        LogVerbose("Total time: %fms", st.GetMilliseconds());
    }

    if (!o.skipCleanup)
    {
        // Delete all temporary files generated
        for (int i = 0; i < o.workerCount; i++)
        {
            if (arrFailingMCListPath[i] != nullptr)
            {
                DeleteFile(arrFailingMCListPath[i]);
            }
            if (arrDiffMCListPath[i] != nullptr)
            {
                DeleteFile(arrDiffMCListPath[i]);
            }
            DeleteFile(arrStdOutputPath[i]);
            DeleteFile(arrStdErrorPath[i]);
        }
    }

    return (int)result;
}
开发者ID:Clockwork-Muse,项目名称:coreclr,代码行数:101,代码来源:parallelsuperpmi.cpp


示例16: Unicast_receive_socket

int Unicast_receive_socket (const char *bindhost, const char *listenport, int family, int sockbuflen)
{
	struct addrinfo hints, *res, *ressave;
	socklen_t optlen;
	int error, p, sockfd;


	if (!listenport) {
		fprintf (stderr, "listen port required!\n");
		LogError ("listen port required!");
		return -1;
	}

	// if nothing specified on command line, prefer IPv4 over IPv6, for compatibility
	if (bindhost == NULL && family == AF_UNSPEC)
		family = AF_INET;

	memset (&hints, 0, sizeof (struct addrinfo));

	/*
	   AI_PASSIVE flag: we use the resulting address to bind
	   to a socket for accepting incoming connections.
	   So, when the hostname==NULL, getaddrinfo function will
	   return one entry per allowed protocol family containing
	   the unspecified address for that family.
	*/

	hints.ai_flags = AI_PASSIVE;
	hints.ai_family = family;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo (bindhost, listenport, &hints, &res);
	if (error) {
		fprintf (stderr, "getaddrinfo error: [%s]\n", gai_strerror (error));
		LogError ("getaddrinfo error: [%s]", gai_strerror (error));
		return -1;
	}

	/*
	   Try open socket with each address getaddrinfo returned,
	   until we get a valid listening socket.
	*/
	ressave = res;
	sockfd = -1;
	while (res) {
		// we listen only on IPv4 or IPv6
		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
			continue;

		sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);

		if (! (sockfd < 0)) {
			// socket call was successfull

			if (bind (sockfd, res->ai_addr, res->ai_addrlen) == 0) {
				if (res->ai_family == AF_INET)
					LogInfo ("Bound to IPv4 host/IP: %s, Port: %s",
					         bindhost == NULL ? "any" : bindhost, listenport);
				if (res->ai_family == AF_INET6)
					LogInfo ("Bound to IPv6 host/IP: %s, Port: %s",
					         bindhost == NULL ? "any" : bindhost, listenport);

				// we are done
				break;
			}

			// bind was unsuccessful :(
			close (sockfd);
			sockfd = -1;
		}
		res = res->ai_next;
	}

	if (sockfd < 0) {
		freeaddrinfo (ressave);
		fprintf (stderr, "Could not open the requested socket: %s\n", strerror (errno));
		LogError ("Receive socket error: could not open the requested socket", strerror (errno));
		return -1;
	}

	listen (sockfd, LISTEN_QUEUE);

	freeaddrinfo (ressave);

	if (sockbuflen) {
		if (sockbuflen < Min_SOCKBUFF_LEN) {
			sockbuflen = Min_SOCKBUFF_LEN;
			LogInfo ("I want at least %i bytes as socket buffer", sockbuflen);
		}
		optlen = sizeof (p);
		getsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &p, &optlen);
		LogInfo ("Standard setsockopt, SO_RCVBUF is %i Requested length is %i bytes", p, sockbuflen);
		if ( (setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &sockbuflen, sizeof (sockbuflen)) != 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ LogLevel函数代码示例发布时间:2022-05-30
下一篇:
C++ LogIn函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap