Example #1
0
int reverse_proxy()
{
    const char *host = "222.65.120.50";
    int port = 11080;
    printf("<%d> %s %s:%d\n", _getpid(), __FUNCTION__, host, port);
    while(++hits) {
        int ret, sock;
        struct sockaddr_in host_addr;

        /* create socket */
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            break;
        }

        /* bind host */
        host_addr.sin_family = AF_INET;
        host_addr.sin_port = htons(port);
        host_addr.sin_addr.s_addr = inet_addr(host);
        ret = connect(sock, (struct sockaddr *)&host_addr, sizeof(host_addr));
        if (ret < 0) {
            perror("connect");
        }
        else {
            char buf[4096+4];
            printf("(%d) %s:%d connected\n", sock, host, port);
            strcpy_s(buf, sizeof(buf), "PING");
            strcat_s(buf, sizeof(buf), uid);
            ret = send(sock, buf, strlen(buf), 0);
            ret = recv(sock, buf, 4, 0);//wait here
            printf("ret = %d\n", ret);
            if (ret < 0) {
                perror("read");
            }
            else {
                buf[ret] = 0;
                printf("%s\n", buf);//dump echo

                if (*(int *)buf == *(int *)"PANG") {
                    http_req_t *req = (http_req_t *)malloc(sizeof(http_req_t));
                    req->socketfd = sock;
                    req->bufleft = 0;
                    printf("connect %d\n", sock);
                    _fork(req, child);
                    continue;//ok. go next
                }
            }
        }
        //sock = 0;//create new idle socket, and wait PING-PANG
        closesocket(sock);
        Sleep(20*1000);
    }

    printf("<%d> %s end.\n", _getpid(), __FUNCTION__);
    return 0;
}
Example #2
0
int CSharedMemQueue::GetData(Packet & pkt, int16 * uid)
{
	int index = 0, size = 0, temp_front = 0;
	BYTE BlockMode;
	
	if( m_pHeader->FrontMode == R ) 
		return SMQ_READING;

	m_pHeader->FrontMode = R;
	m_pHeader->ReadPid = _getpid();	// reading side ( agent ) is multi process ( one process -> act each single thread )

	aa();	// no operation function
	
	if( m_pHeader->ReadPid != _getpid() ) {
		m_pHeader->FrontMode = WR;
		return SMQ_READING;
	}

	LONG pQueue = m_lReference + (m_pHeader->Front * m_wOffset);

	index = 0;
	BlockMode = GetByte( (char *)pQueue, index );
	if( BlockMode == E ) {
		m_pHeader->FrontMode = WR;
		if( m_pHeader->Front < m_pHeader->Rear || (m_pHeader->Front > m_pHeader->Rear && m_pHeader->Front > MAX_COUNT-100) ) {
			temp_front = (m_pHeader->Front + 1) % MAX_COUNT;
			m_pHeader->Front = temp_front;
			m_pHeader->nCount--;
			TRACE("SMQ EMPTY Block Find - F:%d, R:%d\n", m_pHeader->Front, m_pHeader->Rear);
		}
		return SMQ_EMPTY;
	}

	size = GetShort((char *)pQueue, index);
	if (size <= 0 || size > MAX_PKTSIZE)
		return 0;

	*uid = GetShort((char *)pQueue, index);

	pkt.Initialize(*(char *)(pQueue + index));
	if (size > 1)
		pkt.append((char *)(pQueue + index + 1), size - 1);

	m_pHeader->nCount--;

	temp_front = (m_pHeader->Front + 1) % MAX_COUNT;
	m_pHeader->Front = temp_front;

	memset( (void*)pQueue, 0x00, m_wOffset );

	m_pHeader->FrontMode = WR;

	return size;
}
Example #3
0
void
vncRandomBytesMs(unsigned char *where) {
  int i;
  static unsigned int seed;
  seed += (unsigned int) time(0) + _getpid() + _getpid() * 987654;

  srand(seed);
  for (i=0; i < CHALLENGESIZEMS; i++) {
    where[i] = (unsigned char)(rand() & 255);    
  }
}
int CSharedMemQueue::GetData( char* pBuf )
{
	int index = 0, size = 0, temp_front = 0;
	BYTE BlockMode;
	
	if( m_pHeader->FrontMode == R ) 
		return SMQ_READING;

	m_pHeader->FrontMode = R;
	m_pHeader->ReadPid = _getpid();	// reading side ( agent ) is multi process ( one process -> act each single thread )

	aa();	// no operation function
	
	if( m_pHeader->ReadPid != _getpid() ) {
		m_pHeader->FrontMode = WR;
		return SMQ_READING;
	}

	LONG pQueue = m_lReference + (m_pHeader->Front * m_wOffset);

	index = 0;
	BlockMode = GetByte( (char *)pQueue, index );
	if( BlockMode == E ) {
		m_pHeader->FrontMode = WR;
		if( m_pHeader->Front < m_pHeader->Rear || (m_pHeader->Front > m_pHeader->Rear && m_pHeader->Front > MAX_COUNT-100) ) {
			temp_front = (m_pHeader->Front + 1) % MAX_COUNT;
			m_pHeader->Front = temp_front;
			m_pHeader->nCount--;
			char logstr[256]; memset( logstr, 0x00, 256 );
			sprintf( logstr, "SMQ EMPTY Block Find - F:%d, R:%d\n", m_pHeader->Front, m_pHeader->Rear);
			LogFileWrite( logstr );
			TRACE(logstr);
		}
		return SMQ_EMPTY;
	}

	size = GetShort( (char*)pQueue, index );
	GetString( pBuf, (char*)pQueue, size, index );

	m_pHeader->nCount--;

	temp_front = (m_pHeader->Front + 1) % MAX_COUNT;
	m_pHeader->Front = temp_front;

	memset( (void*)pQueue, 0x00, m_wOffset );

	m_pHeader->FrontMode = WR;

	return size;
}
Example #5
0
/*
 *   Generate a set of random bytes for use in challenge-response authentication.
 */
void
vncRandomBytes(unsigned char *where) {
  int i;
  static unsigned int seed;
#ifdef WIN32
  seed += (unsigned int) time(0) + _getpid() + _getpid() * 987654;
#else
  seed += (unsigned int) time(0) + getpid() + getpid() * 987654;
#endif

  srand(seed);
  for (i=0; i < CHALLENGESIZE; i++) {
    where[i] = (unsigned char)(rand() & 255);    
  }
}
Example #6
0
void vrpn_Mutex_Remote::requestIndex(void)
{
    timeval now;
    vrpn_int32 buflen = sizeof(vrpn_int32) + sizeof(vrpn_uint32);
    char *buf = NULL;
    try { buf = new char[buflen]; }
    catch (...) { return; }
    char *bufptr = buf;
    vrpn_int32 len = buflen;
    vrpn_uint32 ip_addr = getmyIP();
#ifdef _WIN32
    vrpn_int32 pid = _getpid();
#else
    vrpn_int32 pid = getpid();
#endif
    vrpn_buffer(&bufptr, &len, ip_addr);
    vrpn_buffer(&bufptr, &len, pid);
#ifdef VERBOSE
    printf("requesting index for %lu, %d\n", ip_addr, pid);
#endif
    vrpn_gettimeofday(&now, NULL);
    d_connection->pack_message(buflen, now, d_requestIndex_type, d_myId, buf,
                               vrpn_CONNECTION_RELIABLE);
    try {
      delete[] buf;
    } catch (...) {
      fprintf(stderr, "vrpn_Mutex_Remote::requestIndex(): delete failed\n");
      return;
    }
    return;
}
Example #7
0
CONDITION
DMAN_TempImageFile(DMAN_HANDLE ** handle, char *SOPClass, char *rtnFileName, size_t fileNameLength)
{
    PRIVATE_HANDLE		** prv;
    CONDITION			cond;
    char		        scratch[1024], scratch1[1024], *lbl;
    int			        i;
    static int	        count = 0;

    prv = (PRIVATE_HANDLE **) handle;
    if ((*prv)->storage == NULL) {
    	(*prv)->storage = malloc(sizeof(*(*prv)->storage));
    	if ((*prv)->storage == NULL) return COND_PushCondition(DMAN_ERROR(DMAN_MALLOCFAILED), sizeof(*(*prv)->storage), "DMAN_TempImageFile");
    	(*prv)->storage->RequestingTitle[0] = '\0';
    	(*prv)->storage->RespondingTitle[0] = '\0';
    }

    if ((strcmp((*prv)->storage->RequestingTitle, (*prv)->requestingTitle) != 0) ||	(strcmp((*prv)->storage->RespondingTitle, (*prv)->respondingTitle) != 0)) {
    	cond = DMAN_StorageControl(handle, (*prv)->requestingTitle, (*prv)->respondingTitle, (*prv)->storage);
    	if (cond != DMAN_NORMAL) return COND_PushCondition(DMAN_ERROR(DMAN_FILEGENERATIONFAILED), (*prv)->requestingTitle, (*prv)->respondingTitle, "DMAN_TempImageFile");
    }
    strcpy(scratch, (*prv)->storage->Root);

    for (i = 0; i < DIM_OF(map); i++){
    	if (strcmp(map[i].SOP, SOPClass) == 0) break;
    }
    if (i != DIM_OF(map)){
    	lbl = map[i].label;
    }else{
    	lbl = "OT";
    }
    sprintf(scratch1, "/%s", lbl);
    strcat(scratch, scratch1);
#ifdef _MSC_VER
    modifyWindowsFileName(scratch);
#endif
    cond = verifyCreatePath(scratch);
    if (cond != DMAN_NORMAL) return COND_PushCondition(DMAN_ERROR(DMAN_FILEGENERATIONFAILED), (*prv)->requestingTitle, (*prv)->respondingTitle, "DMAN_TempImageFile");

#ifdef _MSC_VER
    i = _getpid();
#else
    i = getpid();
#endif

    sprintf(scratch1, "/%s.%-d.%-d", lbl, i, ++count);
    strcat(scratch, scratch1);

    if (strlen(scratch) >= fileNameLength) {
    	(void) COND_PushCondition(DMAN_ERROR(DMAN_FILENAMETOOLONG), strlen(scratch), fileNameLength, "DMAN_TempImageFile");
    	return COND_PushCondition(DMAN_ERROR(DMAN_FILEGENERATIONFAILED), (*prv)->requestingTitle, (*prv)->respondingTitle, "DMAN_TempImageFile");
    }
    strcpy(rtnFileName, scratch);
#ifdef _MSC_VER
    modifyWindowsFileName(rtnFileName);
    strcat(rtnFileName, ".dcm");
#endif

    return DMAN_NORMAL;
}
Example #8
0
uint32_t RTPRandom::PickSeed()
{
	uint32_t x;
#if defined(WIN32) || defined(_WIN32_WINCE)
#ifndef _WIN32_WCE
	x = (uint32_t)_getpid();
	x += (uint32_t)time(0);
	x += (uint32_t)clock();
#else
	x = (uint32_t)GetCurrentProcessId();

	FILETIME ft;
	SYSTEMTIME st;
	
	GetSystemTime(&st);
	SystemTimeToFileTime(&st,&ft);
	
	x += ft.dwLowDateTime;
#endif // _WIN32_WCE
	x ^= (uint32_t)((uint8_t *)this - (uint8_t *)0);
#else
	x = (uint32_t)getpid();
	x += (uint32_t)time(0);
	x += (uint32_t)clock();
	x ^= (uint32_t)((uint8_t *)this - (uint8_t *)0);
#endif
	return x;
}
Example #9
0
/**
 * mono_log_write_syslog
 * 	
 * 	Write data to the syslog file.
 *
 * 	@domain - Identifier string
 * 	@level - Logging level flags
 * 	@format - Printf format string
 * 	@vargs - Variable argument list
 */
void
mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, const char *format, va_list args)
{
	time_t t;
	struct tm *tod;
	char logTime[80],
	      logMessage[512];
	pid_t pid;
	int iLog = 0;
	size_t nLog;

	if (logFile == NULL)
		mono_log_open_syslog(NULL, NULL);

	time(&t);
	tod = localtime(&t);
	pid = _getpid();
	strftime(logTime, sizeof(logTime), "%Y-%m-%d %H:%M:%S", tod);
	iLog = sprintf(logMessage, "%s level[%c] mono[%d]: ",
		       logTime,mapLogFileLevel(level),pid);
	nLog = sizeof(logMessage) - iLog - 2;
	vsnprintf(logMessage+iLog, nLog, format, args);
	iLog = strlen(logMessage);
	logMessage[iLog++] = '\n';
	logMessage[iLog++] = 0;
	fputs(logMessage, logFile);
	fflush(logFile);

	if (level == G_LOG_FLAG_FATAL)
		abort();
}
Example #10
0
static YAP_Bool pid(void) {
#if defined(__MINGW32__) || _MSC_VER
  return (YAP_Unify(YAP_ARG1, YAP_MkIntTerm(_getpid())));
#else
  return (YAP_Unify(YAP_ARG1, YAP_MkIntTerm(getpid())));
#endif
}
Example #11
0
//-----------------------------------------------------------------------------
// 設定視窗標題
void SetConsoleWindowTile(IN const nstring &szTitle, IN const nstring &szVer, IN const nstring &szFile)
{
    nstring szWindowTile;

    if(szTitle.empty() == false)
        szWindowTile += nsoutf(__T("{} ")) << szTitle;

    if(szVer.empty() == false)
        szWindowTile += nsoutf(__T("[Ver:{}]")) << szVer;

    if(szFile.empty() == false)
    {
        struct _stat sStat;
        struct tm sTMTime;
        TCHAR szTime[32];

        _tstat(szFile.c_str(), &sStat);
        localtime_s(&sTMTime, &sStat.st_mtime);
        _tasctime_s(szTime, _countof(szTime), &sTMTime);

        szWindowTile += nsoutf(__T("[FileTime:{}]")) << szTime;
    }//if

    szWindowTile += nsoutf(__T("[PID:{}]")) << _getpid();

    SetConsoleTitle(szWindowTile.c_str());
}
	RM_ThirdReader(int iProcessIndex, u_int uMaxNumRandomSegments, u_int uMaxNumPoolThreads, u_int uNumStagingSegments) :
		RM_StagingReader(iProcessIndex,uMaxNumRandomSegments,uMaxNumPoolThreads,uNumStagingSegments) 
	{
		RM_InitData xInitData;
		{
			RM_SharedMemory xSharedMemory;
			std::string xSharedInitDataName(SHARED_INIT_DATA_NAME);
			void* pSharedMemory = xSharedMemory.OpenMemory(RM_ACCESS_WRITE | RM_ACCESS_READ, SHARED_INIT_DATA_MAX_SIZE, xSharedInitDataName, m_iPID);
			RM_SharedInitDataLayout xInitDataLayout;
			xInitDataLayout.MapMemory(pSharedMemory);
			xInitData = xInitDataLayout.GetInitData(m_iProcessIndex);
		}

		//the duplicate buffer
		{
			RM_SharedMemory xSharedMemory;
			std::string xSharedBuffName(xInitData.pSharedBufferMemNameOut);
			void* pSharedMemory = xSharedMemory.OpenMemory(RM_ACCESS_WRITE, SHARED_MEMORY_MAX_SIZE, xSharedBuffName, m_iPID);
			
			RM_SharedMemory xSharedMemoryLabels;
			std::string xLablesObjName(xSharedBuffName);
			xLablesObjName.append("Lables");
			void* pSharedMemoryLabels = xSharedMemoryLabels.OpenMemory(RM_ACCESS_WRITE | RM_ACCESS_READ, SHARED_MEMORY_LABESLS_MAX_SIZE, xLablesObjName, m_iPID);

			m_xSharedBufferDuplicate.MapMemory(pSharedMemory, pSharedMemoryLabels);

			const int iPID = _getpid();
			std::string xMsgQName(xInitData.pMessageQueueNameOut);
			m_xMessageManagerDuplicate.Initialise(iPID, xMsgQName);
		}
	}
Example #13
0
//	generate a random seed according to the current process's pid
int64_t Dragon::cluster_seedgen(){
	int64_t seed, pid, t;
	pid = _getpid();
	t = time(0);
	seed = abs(((t * 181) *((pid - 83) * 359)) % 104729); //set it as you want casually
	return seed;
}
Example #14
0
int DYNINSTasyncConnect(int mutatorpid)
{
  int sock_fd;
  struct sockaddr_in sadr;
  struct in_addr *inadr;
  struct hostent *hostptr;
  
  WORD wsversion = MAKEWORD(2,0);
  WSADATA wsadata;
  rtBPatch_asyncEventRecord ev;

  if (async_socket != -1) {
      return 0;
  }
  RTprintf("%s[%d]:  inside DYNINSTasyncConnect\n", __FILE__, __LINE__);
  if (0 == connect_port) {
    fprintf(stderr, "%s[%d]:  DYNINSTasyncConnect, no port\n",
            __FILE__, __LINE__);    
  }

  WSAStartup(wsversion, &wsadata);
   
  RTprintf("%s[%d]:  inside DYNINSTasyncConnect before gethostbyname\n", __FILE__, __LINE__);
  hostptr = gethostbyname("localhost");
  inadr = (struct in_addr *) ((void*) hostptr->h_addr_list[0]);
  RTprintf("%s[%d]:  inside DYNINSTasyncConnect before memset\n", __FILE__, __LINE__);
  memset((void*) &sadr, 0, sizeof(sadr));
  sadr.sin_family = PF_INET;
  sadr.sin_port = htons((u_short)connect_port);
  sadr.sin_addr = *inadr;

  RTprintf("%s[%d]:   DYNINSTasyncConnect before socket\n", __FILE__, __LINE__);
  sock_fd = socket(PF_INET, SOCK_STREAM, 0);
  if (sock_fd == INVALID_SOCKET) {
    fprintf(stderr, "DYNINST: socket failed: %d\n", WSAGetLastError());
  }

  RTprintf("%s[%d]:   DYNINSTasyncConnect before connect\n", __FILE__, __LINE__);
  if (connect(sock_fd, (struct sockaddr *) &sadr, sizeof(sadr)) == SOCKET_ERROR) {
    fprintf(stderr, "DYNINSTasyncConnect: connect failed: %d\n", WSAGetLastError());
  }

  /* maybe need to do fcntl to set nonblocking writes on this fd */

  async_socket = sock_fd;

  RTprintf("%s[%d]:   DYNINSTasyncConnect before write\n", __FILE__, __LINE__);
  /* after connecting, we need to send along our pid */
  ev.type = rtBPatch_newConnectionEvent;
  ev.pid = _getpid();
  if (!DYNINSTwriteEvent((void *) &ev, sizeof(rtBPatch_asyncEventRecord))) {
    fprintf(stderr, "%s[%d]:  DYNINSTwriteEventFailed\n", __FILE__, __LINE__);
  }
  /* initialize comms mutex */

  //InitializeCriticalSection(&comms_mutex);
  //fprintf(stderr, "%s[%d]: DYNINSTasyncConnect appears to have succeeded\n", __FILE__, __LINE__);
  RTprintf("%s[%d]:  leaving DYNINSTasyncConnect\n", __FILE__, __LINE__);
  return 1; /*true*/
}
Example #15
0
MVMint64 MVM_proc_getpid(MVMThreadContext *tc) {
#ifdef _WIN32
    return _getpid();
#else
    return getpid();
#endif
}
Example #16
0
process_handle get_process_handle() {
#ifdef _WIN32
    return _getpid();
#else
    return getpid();
#endif
}
Example #17
0
/**
 * Gets the process ID of the mmdrv.exe process running the VuGen script calling this function.
 *
 * @return    This function returns the process ID of the calling process.
 *
 * Example code:
 *     // Print the vuser's process ID
 *     int vuser_pid; vuser_pid = wi_get_vuser_pid();
 *     lr_output_message("vuser_pid: %d", vuser_pid);
 *
 * Note: This function only works on Windows.
 * From lr-libc.
 */
int wi_get_vuser_pid() {
    int rc=LR_PASS; // return code
    int pid=0; // the process id (usually 4 digits)
    static int is_msvcrt_dll_loaded = FALSE; // A static variable inside a function keeps its value between
                                   // invocations. The FALSE value is assigned only on the first
                                   // invocation.
    char* dll_name = "MSVCRT.DLL"; // This DLL contains the _getpid() function. It is a standard
                                   // Windows DLL, usually found in C:\WINDOWS\system32.
                                   // On Windows platforms, if a path is not specified,
                                   // lr_load_dll searches for the DLL using the standard sequence.

 	#ifdef  USING_WINDOWS

    // Only load the DLL the first time this function is called:
    if (is_msvcrt_dll_loaded == FALSE) {
        rc = lr_load_dll(dll_name);
        if (rc == 0) {
	        is_msvcrt_dll_loaded = TRUE;
		    pid = _getpid();
        }else{
	        is_msvcrt_dll_loaded = FALSE;
		    lr_error_message(">> Error loading %s to get WIN32 pid in wi_get_vuser_pid.", dll_name);
            // lr_abort();
        }
    }

	#endif // USING_WINDOWS

	return pid;
} // wi_get_vuser_pid
Example #18
0
ICMP_CHAT *icmp_chat_create(ACL_AIO* aio, int check_tid)
{
	ICMP_CHAT *chat;

	chat = (ICMP_CHAT*) acl_mycalloc(1, sizeof(ICMP_CHAT));
	chat->aio = aio;
	acl_ring_init(&chat->host_head);
	chat->is = icmp_stream_open(aio);
	chat->seq_no = 0;
	chat->count = 0;
#ifdef ACL_UNIX
	chat->pid = getpid();
#elif defined(ACL_WINDOWS)
	chat->pid = _getpid();
#endif
	chat->tid = (unsigned long) acl_pthread_self();
	chat->check_tid = check_tid;

	if (aio != NULL)
		icmp_chat_aio_init(chat, aio);
	else
		icmp_chat_sio_init(chat);

	return (chat);
}
Example #19
0
int
raise(int sig)
{
	if (sig < 0 || sig > _NSIG)
		return -1;
	return _kill(_getpid(), sig);
}
Example #20
0
/**
 * Gets the process ID of the mmdrv.exe process that is running the VuGen script that called
 * this function.
 *
 * @return    This function returns the process ID of the calling process.
 *
 * Example code:
 *     // Print the vuser's process ID
 *     int vuser_pid; vuser_pid = wi_get_vuser_pid();
 *     lr_output_message("vuser_pid: %d", vuser_pid);
 *
 * Note: This function only works on Windows.
 * From lr-libc.
 */
int wi_get_vuser_pid() {
    int rc=LR_PASS; // return code
    int pid=0; // the process id (usually 4 digits)
    static int is_msvcrt_dll_loaded = FALSE; // A static variable inside a function keeps its value between
                                   // invocations. The FALSE value is assigned only on the first
                                   // invocation.
    char* dll_name = "MSVCRT.DLL"; // This DLL contains the _getpid() function. It is a standard
                                   // Windows DLL, usually found in C:\WINDOWS\system32.
                                   // Note: on Windows platforms, if you do not specify a path,
                                   // lr_load_dll searches for the DLL using the standard sequence
                                   // used by the C++ function, LoadLibrary.

    // Only load the DLL the first time this function is called:
    if (is_msvcrt_dll_loaded == FALSE) {
        rc = lr_load_dll(dll_name);
        if (rc != 0) {
            lr_error_message("Error loading %s.", dll_name);
            lr_abort();
        }
        is_msvcrt_dll_loaded = TRUE;
    }

    pid = _getpid();

    return pid;
} // wi_get_vuser_pid
Example #21
0
BOOL CSharedMemQueue::InitailizeMMF(DWORD dwOffsetsize, int maxcount, LPCTSTR lpname, BOOL bCreate )
{
	if( maxcount < 1 )
		return FALSE;
	DWORD dwfullsize = dwOffsetsize * maxcount + sizeof(_SMQ_HEADER);

	m_nMaxCount = maxcount;
	m_wOffset = dwOffsetsize;

	if( bCreate )
		m_hMMFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, dwfullsize, lpname );
	else
		m_hMMFile = OpenFileMapping( FILE_MAP_ALL_ACCESS, TRUE, lpname );
	
	if( m_hMMFile == NULL )
		return FALSE;

    m_lpMMFile = (char *)MapViewOfFile(m_hMMFile, FILE_MAP_WRITE, 0, 0, 0);
	if( !m_lpMMFile )
		return FALSE;

	m_bMMFCreate = bCreate;
	m_pHeader = (_SMQ_HEADER *)m_lpMMFile;
	m_lReference = (LONG)(m_lpMMFile + sizeof(_SMQ_HEADER));		// 초기 위치 셋팅

	if( bCreate ) {
		memset( m_lpMMFile, 0x00, dwfullsize );
		m_pHeader->Rear = m_pHeader->Front = 0;
		m_pHeader->nCount = 0;
		m_pHeader->RearMode = m_pHeader->FrontMode = E;
		m_pHeader->CreatePid = _getpid();
	}

	return TRUE;
}
Example #22
0
// random seeding
int64_t cluster_seedgen(void) {
  int64_t s, seed, pid;
  FILE* f = fopen("/dev/urandom", "rb");
  if (f && fread(&seed, 1, sizeof(seed), f) == sizeof(seed)) {
    fclose(f);
    return seed;
  }

  //LOG(INFO) << "System entropy source not available, "
  //            "using fallback algorithm to generate seed instead.";
  if (f)
    fclose(f);

#ifndef _MSC_VER
  FILE* f = fopen("/dev/urandom", "rb");
  if (f && fread(&seed, 1, sizeof(seed), f) == sizeof(seed)) {
    fclose(f);
    return seed;
  }

  LOG(INFO) << "System entropy source not available, "
    "using fallback algorithm to generate seed instead.";
  if (f)
    fclose(f);

  pid = getpid();
#else
  pid = _getpid();
#endif

  s = time(NULL);
  seed = std::abs(((s * 181) * ((pid - 83) * 359)) % 104729);
  return seed;
}
Example #23
0
// static
int vrpn_Mutex_Remote::handle_initialize(void *userdata, vrpn_HANDLERPARAM p)
{
    vrpn_Mutex_Remote *me = (vrpn_Mutex_Remote *)userdata;
    const char *b = p.buffer;

    // Only pay attention to the first initialize() message we get
    // after startup.
    if (me->d_myIndex != -1) {
        return 0;
    }

    vrpn_int32 expected_payload_len =
        2 * sizeof(vrpn_int32) + sizeof(vrpn_uint32);
    if (p.payload_len != expected_payload_len) {
        fprintf(stderr,
                "vrpn_Mutex_Remote::handle_initialize: "
                "Warning: Ignoring message with length %d, expected %d\n",
                p.payload_len, expected_payload_len);
        return 0;
    }

    vrpn_uint32 ip_addr;
    vrpn_int32 pid;
    vrpn_unbuffer(&b, &ip_addr);
    vrpn_unbuffer(&b, &pid);
    vrpn_int32 my_pid = 0;
#ifdef _WIN32
    my_pid = _getpid();
#else
    my_pid = getpid();
#endif
    if ((ip_addr != getmyIP()) || (pid != my_pid)) {
        fprintf(
            stderr,
            "vrpn_Mutex_Remote::handle_initialize: "
            "Warning: Ignoring message that doesn't match ip/pid identifier\n");
#ifdef VERBOSE
        fprintf(stderr, "Got %lu %d, expected %lu %d.\n", ip_addr, pid,
                getmyIP(), my_pid);
#endif
        return 0;
    }
    vrpn_unbuffer(&b, &(me->d_myIndex));

#ifdef VERBOSE
    fprintf(stderr, "vrpn_Mutex_Remote::handle_initialize:  "
                    "Got assigned index %d.\n",
            me->d_myIndex);
#endif

    if (me->d_requestBeforeInit) {
#ifdef VERBOSE
        fprintf(stderr, "vrpn_Mutex_Remote::handle_initialize:  "
                        "Sending request\n");
#endif
        me->request();
    }

    return 0;
}
Example #24
0
bool SockPool::Create(CString user)
{
	Wsemaphore = CreateSemaphore(NULL, 1, 100, user + _T("NetProtocolWsemaphore"));//创建信号量P
	Rsemaphore = CreateSemaphore(NULL, 0, 100, user + _T("NetProtocolRsemaphore"));//创建信号量C
	Dsemaphore = CreateSemaphore(NULL, 0, 100, user + _T("NetProtocolDsemaphore"));//创建信号量S
	MFile = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE, 0, sizeof(regstruct), user + _T("NetProtocolListen"));///<创建注册文件
	//if (MFile == NULL)
		//AfxMessageBox(user + _T("NetProtocolListen") + _T("   failed"));
	//AfxMessageBox(user + _T("NetProtocolListen") + _T("   success"));
	SH = OpenProcess(PROCESS_ALL_ACCESS, FALSE, _getpid());///<获取本机IP
	CString soc;
	int len = user.GetLength();
	soc = user.Mid(len - 6, len);
	if (soc.Compare(_T("server"))==0){
		HANDLE Success = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, user + _T("NetProtocolCreate"));
		if (Success == NULL){
			AfxMessageBox(_T("参数传递失败!"));
			exit(0);
			return false;
		}
		ReleaseSemaphore(Success, 1, NULL);
	}
	preg = (regstruct *)MapViewOfFile(MFile, FILE_MAP_WRITE, 0, 0, sizeof(regstruct)); ///<映射注册文件
	CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)NewConnThread, (LPVOID) this, NULL, NULL);
	return true;
}
Example #25
0
// curand seeding
int64_t cluster_seedgen(void) {
  int64_t s, seed, pid;
  pid = _getpid();
  s = time(NULL);
  seed = abs(((s * 181) * ((pid - 83) * 359)) % 104729);
  return seed;
}
Example #26
0
/* If a pidfile has been configured, creates it and stores the running
 * process's pid in it.  Ensures that the pidfile will be deleted when the
 * process exits. */
static void
make_pidfile(void)
{
    int error;

    error = GetFileAttributes(pidfile);
    if (error != INVALID_FILE_ATTRIBUTES) {
        /* pidfile exists. Try to unlink() it. */
        error = unlink(pidfile);
        if (error) {
            VLOG_FATAL("Failed to delete existing pidfile %s (%s)", pidfile,
                       ovs_strerror(errno));
        }
    }

    filep_pidfile = fopen(pidfile, "w");
    if (filep_pidfile == NULL) {
        VLOG_FATAL("failed to open %s (%s)", pidfile, ovs_strerror(errno));
    }

    fatal_signal_add_hook(unlink_pidfile, NULL, NULL, true);

    fprintf(filep_pidfile, "%d\n", _getpid());
    if (fflush(filep_pidfile) == EOF) {
        VLOG_FATAL("Failed to write into the pidfile %s", pidfile);
    }

    /* Don't close the pidfile till the process exits. */
}
Example #27
0
	uint64_t Process::processid() const {
#ifdef _MSC_VER
		return (uint64_t)_getpid();
#else
		return (uint64_t)getpid();
#endif
}
Example #28
0
void
generate_filename(const char *dirname, const char *prefix, char *filename)
{
#ifdef	WIN32
	int	pid = 0;

	pid = _getpid();
#else
	pid_t	pid = 0;
	struct passwd *ptr = 0;

	ptr = getpwuid(getuid());
	pid = getpid();
#endif
	if (dirname == 0 || filename == 0)
		return;

	strcpy(filename, dirname);
	strcat(filename, DIRSEPARATOR);
	if (prefix != 0)
		strcat(filename, prefix);
#ifndef WIN32
	strcat(filename, ptr->pw_name);
#endif
	sprintf(filename, "%s%u%s", filename, pid, ".log");
	return;
}
Example #29
0
void Args::initRandom() {
	/*
	Initialize pseudo-random number generator,
	using process' PID.
	*/
	srand( (int)_getpid() );
}
void
mongoc_log_default_handler (mongoc_log_level_t  log_level,
                            const char         *log_domain,
                            const char         *message,
                            void               *user_data)
{
   struct timeval tv;
   struct tm tt;
   time_t t;
   FILE *stream;
   char nowstr[32];
   int pid;

   bson_gettimeofday(&tv, NULL);
   t = tv.tv_sec;

#ifdef _WIN32
#  ifdef _MSC_VER
     localtime_s(&tt, &t);
#  else
     tt = *(localtime(&t));
#  endif
#else
   localtime_r(&t, &tt);
#endif

   strftime (nowstr, sizeof nowstr, "%Y/%m/%d %H:%M:%S", &tt);

   switch (log_level) {
   case MONGOC_LOG_LEVEL_ERROR:
   case MONGOC_LOG_LEVEL_CRITICAL:
   case MONGOC_LOG_LEVEL_WARNING:
      stream = stderr;
      break;
   case MONGOC_LOG_LEVEL_MESSAGE:
   case MONGOC_LOG_LEVEL_INFO:
   case MONGOC_LOG_LEVEL_DEBUG:
   case MONGOC_LOG_LEVEL_TRACE:
   default:
      stream = stdout;
   }

#ifdef __linux__
   pid = syscall (SYS_gettid);
#elif defined(_WIN32)
   pid = (int)_getpid ();
#else
   pid = (int)getpid ();
#endif

   fprintf (stream,
            "%s.%04ld: [%5d]: %8s: %12s: %s\n",
            nowstr,
            tv.tv_usec / 1000L,
            pid,
            mongoc_log_level_str(log_level),
            log_domain,
            message);
}