Ejemplo n.º 1
0
char *BatchLink( char *name )
{
    if( name == NULL ) name = DEFAULT_NAME;
    SemReadUp = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, READUP_NAME );
    SemReadDone = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, READDONE_NAME );
    SemWritten = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, WRITTEN_NAME );
    MemHdl = OpenFileMapping( FILE_MAP_WRITE, FALSE, SHARED_MEM_NAME );
    if( MemHdl == NULL || SemReadUp == NULL || SemWritten == NULL ) {
        return( "can not connect to batcher spawn server" );
    }
    SharedMem = MapViewOfFile( MemHdl, FILE_MAP_WRITE, 0, 0, 0 );
    return( NULL );
}
Ejemplo n.º 2
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;
}
FWindowsPlatformProcess::FSemaphore * FWindowsPlatformProcess::NewInterprocessSynchObject(const FString & Name, bool bCreate, uint32 MaxLocks)
{
	HANDLE Semaphore = NULL;
	
	if (bCreate)
	{
		Semaphore = CreateSemaphore(NULL, MaxLocks, MaxLocks, *Name);
		if (NULL == Semaphore)
		{
			DWORD ErrNo = GetLastError();
			UE_LOG(LogHAL, Warning, TEXT("CreateSemaphore(Attrs=NULL, InitialValue=%d, MaxValue=%d, Name='%s') failed with LastError = %d"),
				MaxLocks, MaxLocks,
				*Name,
				ErrNo);
			return NULL;
		}
	}
	else
	{
		DWORD AccessRights = SYNCHRONIZE | SEMAPHORE_MODIFY_STATE;
		Semaphore = OpenSemaphore(AccessRights, false, *Name);
		if (NULL == Semaphore)
		{
			DWORD ErrNo = GetLastError();
			UE_LOG(LogHAL, Warning, TEXT("OpenSemaphore(AccessRights=0x%08x, bInherit=false, Name='%s') failed with LastError = %d"),
				AccessRights,
				*Name,
				ErrNo);
			return NULL;
		}
	}
	check(Semaphore);

	return new FWindowsSemaphore(Name, Semaphore);
}
Ejemplo n.º 4
0
/**
* @author ACM2012
* @note  监听线程注册,若有线程注册,创建读写队列并初始化,创建线程对队列进行读写
*/
void SockPool::Connect()
{
		while (state){
			WaitForSingleObject(Dsemaphore, INFINITE);//等待应用程序请求连接
			PM pReadQueue, pWriteQueue;
	        HANDLE CH,ReadQueue, WriteQueue;
			HANDLE CDestory, SDestory;
			struct Para rPara, wPara;

			AllocResource(preg->SockMark);///<为套接字分配资源
			ReadQueue = OpenFileMapping(FILE_MAP_WRITE, FALSE, preg->WriteQueueName);
			InitalReadQueue(ReadQueue,pReadQueue,CH);///<初始化读队列
			CDestory = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, preg->CDestoryName);
			WriteQueue = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE, 0, sizeof(Manager), preg->ReadQueueName);
			InitalWriteQueue(WriteQueue, pWriteQueue);///<初始化写队列
			SDestory = CreateSemaphore(NULL, 0, 100, preg->SDestoryName);
			InitalThreadPara(rPara, CH, ReadQueue, pReadQueue, preg->SockMark,CDestory);
			CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)NewReadThread, (LPVOID)&rPara, NULL, NULL);
			InitalThreadPara(wPara, CH, WriteQueue, pWriteQueue, preg->SockMark,SDestory);
			CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)NewWriteThread, (LPVOID)&wPara, NULL, NULL);
			ReleaseSemaphore(Rsemaphore, 1, NULL);///<释放读信号量
			sockconnum++;
			//AfxMessageBox(preg->CDestoryName);
			//AfxMessageBox(preg->SDestoryName);
			//AfxMessageBox(preg->ReadQueueName);
			//AfxMessageBox(preg->WriteQueueName);
			CString pid;
			pid.Format(_T("%d"), preg->SockMark);
			//AfxMessageBox(pid);
		}
}
Ejemplo n.º 5
0
THREAD_RETURN WINAPI bgThread4SemTest( LPVOID dum )
{ unsigned long ret;
  double tEnd;
  HANDLE hh;
	MSEmul_UseSharedMemory(true);
	hh = OpenSemaphore( DELETE|SYNCHRONIZE|SEMAPHORE_MODIFY_STATE, false, (char*)"cseSem");
	if( hh ){
#if defined(__windows__)
		fprintf( stderr, "##%lx bgThread4SemTest starting to wait for semaphore (0x%p) release at t=%g\n",
			   GetCurrentThreadId(), hh, HRTime_Time() - tStart );
#else
		fprintf( stderr, "##%lx bgThread4SemTest starting to wait for semaphore (0x%p,%s,%p) release at t=%g\n",
			   GetCurrentThreadId(), hh, hh->d.s.name, hh->d.s.sem, HRTime_Time() - tStart );
#endif
		ret = WaitForSingleObject( hh, INFINITE ); tEnd = HRTime_Time();
		fprintf( stderr, "##%lx WaitForSingleObject( hh, INFINITE ) = %lu at t=%g; sleep(1ms) and ReleaseSemaphore(hh,1,NULL)\n",
			   GetCurrentThreadId(), ret, tEnd - tStart );
		Sleep(1);
		fprintf( stderr, "##%lx t=%g ReleaseSemaphore(hh,1,NULL) = %d\n",
			   GetCurrentThreadId(), HRTime_Time() - tStart, ReleaseSemaphore(hh, 1, NULL) );
		CloseHandle(hh);
  	}
	else{
		fprintf( stderr, "##%lx bgThread4SemTest() couldn't obtain semaphore '%s', will exit\n", GetCurrentThreadId(), "cseSem" );
	}
	return (THREAD_RETURN)3;
}
Ejemplo n.º 6
0
BOOL APIENTRY DllMain( HINSTANCE hModule,
					   DWORD  ul_reason_for_call,
					   LPVOID /*lpReserved*/
					 )
{
	hMod = hModule;
	switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
			hSem = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE,
								 "WinPenguins-DeskPaintSem");
			if (hSem == NULL) {
				hSem = CreateSemaphore(NULL, 1, 1,
									   "WinPenguins-DeskPaintSem");
				assert(hSem != NULL);
			}
			break;

		case DLL_PROCESS_DETACH:
			DeleteObject(hSem);
			break;

		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
			break;

	}
	return TRUE;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
	HANDLE ThreadH[2];
	int iloop;

	gsem = CreateSemaphore(NULL, 1, 1, "TestSem");
	if (gsem == NULL)
	{
		printf("Error %d\n", GetLastError());
		return 1;
	}

	if (OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "TestSem") == NULL)
	{
		printf("Semaphore Open Error %d\n", GetLastError());
		return 1;
	}

	for (iloop = 0; iloop < MAX_THREAD; iloop++)
	{
		printf("Create Thread %d\n", iloop);
		ThreadH[iloop] = CreateThread(NULL, 0, myThread, (void *)&iloop, 0, NULL);
		Sleep(500);
	}
	WaitForMultipleObjects(MAX_THREAD, ThreadH, TRUE, INFINITE);
	CloseHandle(gsem);
	return 0;
}
Ejemplo n.º 8
0
PRSem *_PR_MD_OPEN_SEMAPHORE(
    const char *osname, PRIntn flags, PRIntn mode, PRUintn value)
{
    PRSem *sem;
    SECURITY_ATTRIBUTES sa;
    LPSECURITY_ATTRIBUTES lpSA = NULL;
    PSECURITY_DESCRIPTOR pSD = NULL;
    PACL pACL = NULL;

    sem = PR_NEW(PRSem);
    if (sem == NULL) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        return NULL;
    }
    if (flags & PR_SEM_CREATE) {
        if (_PR_NT_MakeSecurityDescriptorACL(mode, semAccessTable,
                                             &pSD, &pACL) == PR_SUCCESS) {
            sa.nLength = sizeof(sa);
            sa.lpSecurityDescriptor = pSD;
            sa.bInheritHandle = FALSE;
            lpSA = &sa;
        }
        sem->sem = CreateSemaphore(lpSA, value, 0x7fffffff, osname);
        if (lpSA != NULL) {
            _PR_NT_FreeSecurityDescriptorACL(pSD, pACL);
        }
        if (sem->sem == NULL) {
            _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
            PR_DELETE(sem);
            return NULL;
        }
        if ((flags & PR_SEM_EXCL) && (GetLastError() == ERROR_ALREADY_EXISTS)) {
            PR_SetError(PR_FILE_EXISTS_ERROR, ERROR_ALREADY_EXISTS);
            CloseHandle(sem->sem);
            PR_DELETE(sem);
            return NULL;
        }
    } else {
        sem->sem = OpenSemaphore(
                       SEMAPHORE_MODIFY_STATE|SYNCHRONIZE, FALSE, osname);
        if (sem->sem == NULL) {
            DWORD err = GetLastError();

            /*
             * If we open a nonexistent named semaphore, NT
             * returns ERROR_FILE_NOT_FOUND, while Win95
             * returns ERROR_INVALID_NAME
             */
            if (err == ERROR_INVALID_NAME) {
                PR_SetError(PR_FILE_NOT_FOUND_ERROR, err);
            } else {
                _PR_MD_MAP_DEFAULT_ERROR(GetLastError());
            }
            PR_DELETE(sem);
            return NULL;
        }
    }
    return sem;
}
Ejemplo n.º 9
0
//---------------------------------------------------------------------------
void __fastcall TThdSend::NewTask(TQueItf *QueItf)
{
  FQueSend->push(QueItf);

  HANDLE  mx=OpenSemaphore(SEMAPHORE_ALL_ACCESS,true,TRjlFunc::ThrSendMutex.c_str());
  ReleaseSemaphore(mx,1,NULL);
  CloseHandle(mx);
}
Ejemplo n.º 10
0
server::server(char *path) 
{
	ZeroMemory(&StartupInfo, sizeof(StartupInfo));
	StartupInfo.cb = sizeof(StartupInfo);
	ZeroMemory(&ChildProcessInfo, sizeof(ChildProcessInfo));

	size_of_buffer = sizeof(buffer);

	Semaphore_client[0] = CreateSemaphore(NULL, 0, 1, "SEMAPHORE_CLIENT_START_PRINT");
	Semaphore_client[1] = CreateSemaphore(NULL, 0, 1, "SEMAPHORE_CLIENT_END_PRINT");
	Semaphore_client[2] = CreateSemaphore(NULL, 0, 1, "SEMAPHORE_CLIENT_PRINT_EXIT");
	Semaphore_client[3] = CreateSemaphore(NULL, 0, 1, "SEMAPHORE_CLIENT_SEND");
	Semaphore_client[4] = CreateSemaphore(NULL, 0, 1, "SEMAPHORE_CLIENT_SEND_EXIT");

	cout << "Client started..." << endl << endl;

	hNamedPipe = CreateNamedPipe("\\\\.\\pipe\\Pipe",
								PIPE_ACCESS_DUPLEX,
								PIPE_TYPE_MESSAGE | PIPE_WAIT,	// Synchronous messaging
								PIPE_UNLIMITED_INSTANCES,		// The maximum numberber of channels copies
								0,								// The size of the output bufferer 
								0, 
								INFINITE, 
								(LPSECURITY_ATTRIBUTES)NULL		// The default protection
								);

	CreateProcess(path, " 2", NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &StartupInfo, &ChildProcessInfo);

	// Check 
	if (hNamedPipe == INVALID_HANDLE_VALUE)
	{
		cout << "Creation of the named pipe failed.\n";
	}

	if (!ConnectNamedPipe(hNamedPipe, (LPOVERLAPPED)NULL)) 
	{
		cout << "Connection fail.\n";
	}

	Semaphore_server[0] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_START_PRINT");
	Semaphore_server[1] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_END_PRINT");
	Semaphore_server[2] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_PRINT_EXIT");
	Semaphore_server[3] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_SEND");
	Semaphore_server[4] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE,"SEMAPHORE_SERVER_SEND_EXIT");
}
Ejemplo n.º 11
0
rt_private int get_pipe_events (char* id, HANDLE* p_event_r, HANDLE* p_event_w)
{
	HANDLE event_r, event_w;
	CHAR   event_str [128];
	unsigned int debuggee_pid;
	DWORD count;

	/* debuggee/application date */
	debuggee_pid = (unsigned int) GetCurrentProcessId();

	/* Get Semaphore */
	event_r = NULL;

/*      NT 3.51 is really fast - at this point we know we were launched by ebench.
	lets wait for it to catch up with us */

	sprintf (event_str, "eif_event_w%x_%s", debuggee_pid, id);
	for (count = 0; (event_r == NULL) && (count < 10); count++) {
		event_r = OpenSemaphore (SEMAPHORE_ALL_ACCESS, FALSE, event_str);
		if (event_r == NULL)
			Sleep(500);
	}
	if (event_r == NULL) {
#ifdef USE_ADD_LOG
		add_log(12, "not started from wrapper - no read event %d", GetLastError());
#endif
		return -1;
	}
	sprintf (event_str, "eif_event_r%x_%s", debuggee_pid, id);
	event_w = OpenSemaphore (SEMAPHORE_ALL_ACCESS, FALSE, event_str);
	if (event_w == NULL) {
#ifdef USE_ADD_LOG
		add_log(12, "not started from wrapper - no write event");
#endif
		return -1;
	}

	*p_event_r = event_r;
	*p_event_w = event_w;

	return 0;
}
Ejemplo n.º 12
0
void server::server_print() 
{
	HANDLE Semaphores[3];
	Semaphore_server[0] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_START_PRINT");
	Semaphore_server[1] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_END_PRINT");
	Semaphore_server[2] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_PRINT_EXIT");
	Semaphore_server[3] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_SEND");
	Semaphore_server[4] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "SEMAPHORE_SERVER_SEND_EXIT");
	Semaphores[0] = Semaphore_server[0];	//SEMAPHORE_SERVER_START_PRINT
	Semaphores[1] = Semaphore_server[1];	//SEMAPHORE_SERVER_END_PRINT
	Semaphores[2] = Semaphore_server[2];	//SEMAPHORE_SERVER_PRINT_EXIT
	while (1) 
	{
		flag = TRUE;
		DWORD numberber_of_bytes_read;
		print_message.clear();
		int index = WaitForMultipleObjects(3, Semaphores, FALSE, INFINITE) - WAIT_OBJECT_0;
		if (index == 2) break;
		
		int numberber_of_blocks;
		int size;
		if (!ReadFile(hNamedPipe, &numberber_of_blocks, sizeof(numberber_of_blocks), &numberber_of_bytes_read, NULL)) break;
		if (!ReadFile(hNamedPipe, &size, sizeof(size), &numberber_of_bytes_read, NULL)) break;
		for (int i = 0; i < numberber_of_blocks; i++) 
		{
			flag = ReadFile(hNamedPipe, buffer, size_of_buffer, &numberber_of_bytes_read, NULL);
			if (!flag) break;
			print_message.append(buffer, size_of_buffer);	
		}
		if (!flag) break;

		print_message.resize(size);
		print_server();
		for (int i = 0; i < size; i++) 
		{
			cout << print_message[i];
			Sleep(SLEEP_TIME);
		}
		cout << endl;
		ReleaseSemaphore(Semaphore_server[1], 1, NULL);		//SEMAPHORE_SERVER_END_PRINT
	}
}
Ejemplo n.º 13
0
gpointer
ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
{
	HANDLE sem;

	sem = OpenSemaphore (rights, FALSE, mono_string_chars (name));

	*error = GetLastError ();

	return sem;
}
Ejemplo n.º 14
0
client::client() {
	size_of_buff = sizeof(buff);

	Semaphore_client_start_print = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, GetWC("SEMAPHORE_CLIENT_START_PRINT"));
	Semaphore_client_end_print = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, GetWC("SEMAPHORE_CLIENT_END_PRINT"));
	Semaphore_client_print_exit = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, GetWC("SEMAPHORE_CLIENT_PRINT_EXIT"));

	Semaphore_client_send = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, GetWC("SEMAPHORE_CLIENT_SEND"));
	Semaphore_client_send_exit = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, GetWC("SEMAPHORE_CLIENT_SEND_EXIT"));

	Semaphore_server_start_print = CreateSemaphore(NULL, 0, 1, GetWC("SEMAPHORE_SERVER_START_PRINT"));
	Semaphore_server_end_print = CreateSemaphore(NULL, 0, 1, GetWC("SEMAPHORE_SERVER_END_PRINT"));
	Semaphore_server_print_exit = CreateSemaphore(NULL, 0, 1, GetWC("SEMAPHORE_SERVER_PRINT_EXIT"));

	Semaphore_server_send = CreateSemaphore(NULL, 0, 1, GetWC("SEMAPHORE_SERVER_SEND"));
	Semaphore_server_send_exit = CreateSemaphore(NULL, 0, 1, GetWC("SEMAPHORE_SERVER_SEND_EXIT"));

	cout << "Server started..." << endl << endl;

	hPipe = CreateFile(GetWC("\\\\.\\pipe\\Pipe"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
}
Ejemplo n.º 15
0
static os_result
condSignal(
    os_cond *cond,
    long mask)
{
    char name[OS_SERVICE_ENTITY_NAME_MAX];
    HANDLE hQueue;
    DWORD result;
    long oldState;
    os_result osr;

    assert(cond != NULL);

    osr = os_resultSuccess;

    if (cond->scope == OS_SCOPE_SHARED) {

        _snprintf(name, sizeof(name), "%s%s%d%d",
            (os_sharedMemIsGlobal() ? OS_SERVICE_GLOBAL_NAME_PREFIX : ""),
            OS_SERVICE_SEM_NAME_PREFIX,
            cond->qId,
            os_getShmBaseAddressFromPointer(cond));

        hQueue = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name);
        if (hQueue == NULL) {
            OS_DEBUG_1("condSignal", "OpenSemaphore failed %d", (int)GetLastError());
            assert(0);
            return os_resultFail;
        }
    } else {
        hQueue       = (HANDLE)cond->qId;
    }

    oldState = InterlockedOr(&cond->state, mask);
    if (oldState == 0) { /* no waiters */
        InterlockedAnd(&cond->state, ~mask);
        return osr;
    }

    if (mask == BROADCAST_BIT_MASK) {
        result = ReleaseSemaphore(hQueue, oldState, 0);
    } else {
        result = ReleaseSemaphore(hQueue, 1, 0);
    }
    InterlockedAnd(&cond->state, ~mask);

    if (cond->scope == OS_SCOPE_SHARED) {
        CloseHandle(hQueue);
    }

    return osr;
}
Ejemplo n.º 16
0
void CThreadBase::DoRunThreadL()
	{
	CActiveScheduler*  scheduler = NULL;
	scheduler = new (ELeave) CActiveScheduler;
	CleanupStack::PushL(scheduler);
	CActiveScheduler::Install(scheduler);

	OpenSemaphore();
	SetUpTestL( ThreadName() );
	
	ThreadL();
	
	TakeDownTest();
	CloseSemaphore();
	
	CleanupStack::PopAndDestroy(scheduler);
	}
Ejemplo n.º 17
0
DWORD WINAPI Thread(LPVOID lp)
{
	HWND hEdit = (HWND) lp;
	HANDLE h = OpenSemaphore(SEMAPHORE_ALL_ACCESS, false, TEXT("{41B4DBD4-F00A-4999-BFA9-1A20D12591B1}"));
	if (WaitForSingleObject(h, INFINITE) == WAIT_OBJECT_0)
	{
		for (int i = 0; i <= 50; i++)
		{
			TCHAR str[5];
			wsprintf(str, TEXT("%d"), i);
			Sleep(100);
			SetWindowText(hEdit, str);
		}
		ReleaseSemaphore(h, 1, NULL);
	}
	CloseHandle(h);
	return 1;
}
Ejemplo n.º 18
0
DWORD L_CONNECT_response(long source, long destination, int priority)//envia ACK
{
      int ret;
      HANDLE c;
      
      if(mode == 1){printf("\nL_CONNECT_response\n");}
      
      //abrimos el semaforo que indicara que la conexion se ha realizado
      c = OpenSemaphore(SEMAPHORE_ALL_ACCESS,TRUE,"semaphoreConexion");
      
      //creamos y enviamos la trama ACK
      makeFrame(ackFrame,NULL);
      
      //esperamos hasta que nos confirmen la conexion
      ret = WaitForSingleObject(c,timeout);
      
      //si no se ha complido el timeout significa que hemos conseguido conectarnos
      if(ret != WAIT_TIMEOUT){conexionOK = 1;}
             
      return 0;
}
Ejemplo n.º 19
0
	HANDLE getPathSemaphore(char* path, void* sharedMemory) {
		HANDLE pathSemaphore = NULL;

		uint32_t hashedPath = crc32(CRC_HASHING_CONSTANT, path, strlen(path) + 1);

		char* hashedPathString = Malloc(sizeof(char) * BUFFER_SIZE);
		if (snprintf(hashedPathString, BUFFER_SIZE, "%u", hashedPath) < 0) {
			handle_error("Error converting hash to string");
		}

		if ((pathSemaphore = OpenSemaphore(SEMAPHORE_FLAGS, FALSE, hashedPathString)) == NULL) {
			if (GetLastError() != ERROR_FILE_NOT_FOUND) {
				handle_error("Error while opening path semaphore");
			} else {
				pathSemaphore = CREATESemaphore(NULL, 1, 1, hashedPathString);
			}
		}

		free(hashedPathString);
		return pathSemaphore;
	}
Ejemplo n.º 20
0
  Sem::Sem(const char* const   inName,
                       const unsigned long inCount,
                       const unsigned long inMaxCount)
    : theSemaphoreHandle(0),
      theMaxCount(inMaxCount)
  {
    if (theMaxCount == 0 || theMaxCount > 0x7FFFFFFF)
    {
      theMaxCount = 0x7FFFFFFF;
    }

    theSemaphoreHandle = CreateSemaphore(NULL,
                                         inCount > theMaxCount ? theMaxCount : inCount,
                                         theMaxCount,
                                         inName);

    if (theSemaphoreHandle == NULL)
    {
      DWORD rc = GetLastError();

      if (rc == ERROR_ALREADY_EXISTS)
      {
        // semaphore is creted try to open it
        theSemaphoreHandle = OpenSemaphore(SEMAPHORE_ALL_ACCESS | SYNCHRONIZE, FALSE, inName);

        if (theSemaphoreHandle == 0)
        {
          Logger::abort("Semaphore: failed to open.");
        }
      }
      else
      {
        Logger::abort("Semaphore: failed to create.");
      }
    }
  }
Ejemplo n.º 21
0
bool C_IPC_SERVER::Open( char *pszServerName )
{
	if( m_boInited || !IsValidServerName( pszServerName ) ) return false;
	char szFirstPartOfName[ _MAX_PATH ];
	strcpy( szFirstPartOfName, FrefixName() ); strcat( szFirstPartOfName, pszServerName );
	char szName[ _MAX_PATH ];

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_MAPFILE_BUFFER );
	if( !C_IPC_BUFFER::Open( szName ) ) return false;

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_BREAK );
	HANDLE hBreak = OpenEvent( EVENT_ALL_ACCESS, FALSE, szName );
	if( !hBreak )
	{
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_WAIT_BUSY );
	HANDLE hWaitBusy = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, szName );
	if( !hWaitBusy )
	{
		CloseHandle( hBreak );
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_CONNECT_BUSY );
	HANDLE hConnectBusy = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, szName );
	if( !hWaitBusy )
	{
		CloseHandle( hWaitBusy );
		CloseHandle( hBreak );
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_CONNECT_NEW );
	HANDLE hConnect = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, szName );
	if( !hConnect )
	{
		CloseHandle( hConnectBusy );
		CloseHandle( hWaitBusy );
		CloseHandle( hBreak );
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_SEND );
	HANDLE hSend = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, szName );
	if( !hSend )
	{
		CloseHandle( hConnect );
		CloseHandle( hConnectBusy );
		CloseHandle( hWaitBusy );
		CloseHandle( hBreak );
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	strcpy( szName, szFirstPartOfName ); strcat( szName, IPC_ADD_NAME_RECV );
	HANDLE hRecv = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, szName );
	if( !hRecv )
	{
		CloseHandle( hSend );
		CloseHandle( hConnect );
		CloseHandle( hConnectBusy );
		CloseHandle( hWaitBusy );
		CloseHandle( hBreak );
		C_IPC_BUFFER::Close();
		return false;
	}

	//////////////////////////////////////////////

	m_boInited			= true;

	m_hBreak			= hBreak;

	m_hWaitBusy			= hWaitBusy;
	m_hConnectBusy		= hConnectBusy;

	m_hConnectNew		= hConnect;

	m_hSend				= hSend;
	m_hRecv				= hRecv;

	return true;
}
Ejemplo n.º 22
0
EIF_INTEGER ipc_semaphore_open (EIF_POINTER lpName) {
	return (EIF_INTEGER) OpenSemaphore (SEMAPHORE_ALL_ACCESS, TRUE, (LPCTSTR)lpName);
}
Ejemplo n.º 23
0
int CBD1
semctl(int semid, int semnum, int cmd, ...)
{
	BOOL	ret;
	int	iret;
	DWORD	dwret;
	int	i, j, diffsemval;
#ifndef TERMINAL_SERVICE
	char	semstr[16];
#else
	char	semstr[30];
#endif	/* TERMINAL_SERVICE */
	BOOL	lret;
	HANDLE	hsem;
	int	piid;
	DWORD	procid;
	va_list vlist;
	union	semun	semarg;
	LPTSTR	lpszPipeName = "\\\\.\\pipe\\ipcd";
	SCBUF	scIn, scOut;
	DWORD	bytesRead;
	HANDLE	hIpct = NULL;
	IPCT	*ipct = NULL;
#ifdef	TERMINAL_SERVICE
	OSVERSIONINFOEX osvi;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !GetVersionEx ((OSVERSIONINFO *) &osvi) )
	{
	  // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		GetVersionEx( (OSVERSIONINFO *) &osvi );
	}
#endif	/* TERMINAL_SERVICE */

//	StartIPCD();
	if (semid<0 || semid>=MAXNOOFIPC)
	{
		errno=EINVAL;
		return -1;
	}

	if (GetIPCT(&hIpct, &ipct)<0)
	{
		errno=EFAULT;
		return -1;
	}

	if (ipct->semt[semid].key<0)
	{
		procid=GetCurrentProcessId();
		piid=FindPINFO(OPT_SEM, procid, ipct);
		if (piid>=0)
		{
			for (i=0; i<MAXNSEM; i++)
				ipct->pseminfo[piid].semadj[semid][i]=0;
			ipct->pseminfo[piid].semid[semid]=0;
			InitPINFO(OPT_SEM, piid, ipct);
		}
		errno=EINVAL;
		FreeIPCT(hIpct, ipct);
		return -1;
	}

	if (semnum<0 || semnum>ipct->semt[semid].semds.sem_nsems)
	{
		errno=EINVAL;
		FreeIPCT(hIpct, ipct);
		return -1;
	}

	va_start(vlist, cmd);
	semarg=va_arg(vlist, union semun);
	va_end(vlist);

	switch (cmd)
	{
	case	IPC_STAT:
		if (semarg.buf == NULL)
		{
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		memcpy((PSTR)semarg.buf, (PSTR)&ipct->semt[semid].semds,
						sizeof(ipct->semt[semid].semds));
		FreeIPCT(hIpct, ipct);
		return 0;

	case	IPC_RMID:

		scIn.cmd=SNO_SEMCTL;
		scIn.data=semid;

		lret = CallNamedPipe(lpszPipeName,
			 (char *)&scIn, sizeof(scIn),
			 (char *)&scOut, sizeof(scOut),
			 &bytesRead, NMPWAIT_WAIT_FOREVER);

		if (lret==FALSE)
		{
			errno=GetLastError();
			FreeIPCT(hIpct, ipct);
			return -1;
		}
		if (scOut.cmd!=SNO_OK)
		{
			errno=scOut.data;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		if( InitSEMT(semid, ipct) < 0 )
			return -1;

		for (i=0; i<MAXNOOFIPC; i++)
		{
			for (j=0; j<MAXNSEM; j++)
				ipct->pseminfo[i].semadj[semid][j]=0;
			ipct->pseminfo[i].semid[semid]=0;
			InitPINFO(OPT_SEM, i, ipct);
		}


		FreeIPCT(hIpct, ipct);
		return 0;

	case	GETVAL:
		iret=ipct->semb[semid][semnum].semval;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	SETVAL:
		if (semarg.val < 0)
		{
			errno = EINVAL;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		diffsemval=semarg.val-ipct->semb[semid][semnum].semval;

#ifndef TERMINAL_SERVICE
		MakeSemstr(semstr, semnum, semid, ipct->semt[semid].key);
#else
		if( osvi.dwMajorVersion >= 5 )	/* Windows 2000 */
			MakeGlobalSemstr(semstr, semnum, semid, ipct->semt[semid].key);
		else
			MakeSemstr(semstr, semnum, semid, ipct->semt[semid].key);
#endif	/* TERMINAL_SERVICE */
		hsem=OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, semstr);
		if (hsem==NULL)
		{
			errno=GetLastError();
			FreeIPCT(hIpct, ipct);
			return -1;
		}
		for (i=0; i<abs(diffsemval); i++)
		{
			if (diffsemval>0)
			{
				ret=ReleaseSemaphore(hsem, diffsemval, NULL);
				if (ret==FALSE)
				{
					errno=GetLastError();
					CloseHandle(hsem);
					FreeIPCT(hIpct, ipct);
					return -1;
				}
				break;	/*2000.4.19*/
			}
			else if (diffsemval<0)
			{
/********************
				do
				{
					dwret=MsgWaitForMultipleObjects(1, &hsem,
						FALSE, INFINITE,
						QS_SENDMESSAGE|QS_POSTMESSAGE|QS_TIMER);
********************/
				dwret=WaitForSingleObject(hsem, INFINITE);

				switch (dwret)
				{
/********************
				case	WAIT_OBJECT_0 + 1 :
					if (l_peekmessage()<0)
					{
						CloseHandle(hsem);
						FreeIPCT(hIpct, ipct);
						return -1;
					}
					break;
********************/

				case	WAIT_OBJECT_0	:
					break;

				case	WAIT_TIMEOUT	:
				case	WAIT_FAILED	:
					errno=GetLastError();
				default :
					CloseHandle(hsem);
					FreeIPCT(hIpct, ipct);
					return -1;
				}
/*************
				} while (dwret==(WAIT_OBJECT_0 + 1));
*************/
			}
		}
		CloseHandle(hsem);

		ipct->semb[semid][semnum].semval=semarg.val;
		for (i=0; i<MAXNOOFIPC; i++)
			ipct->pseminfo[i].semadj[semid][semnum]=0;

		FreeIPCT(hIpct, ipct);
		return 0;

	case	GETPID:
		iret=ipct->semb[semid][semnum].sempid;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETNCNT:
		iret=ipct->semb[semid][semnum].semncnt;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETZCNT:
		iret=ipct->semb[semid][semnum].semzcnt;
		FreeIPCT(hIpct, ipct);
		return iret;

	case	GETALL:
		if (semarg.array == NULL)
		{
			errno=EINVAL;
			FreeIPCT(hIpct, ipct);
			return -1;
		}

		for (i=0; i<ipct->semt[semid].semds.sem_nsems; i++)
			semarg.array[i]=(short)ipct->semb[semid][i].semval;

		FreeIPCT(hIpct, ipct);
		return 0;

	case	SETALL:
		/* #####PENDING */
		FreeIPCT(hIpct, ipct);
		return 0;

	default:
		FreeIPCT(hIpct, ipct);
		return -1;
	}

}
Ejemplo n.º 24
0
//---------------------------------------------------------------------------
void __fastcall TThdSend::Execute()
{
  double  p;
  int     n,un;
  bool    undoall = false;
  TBourse bourse;
  HANDLE  hMutex=OpenSemaphore(SEMAPHORE_ALL_ACCESS	,true,TRjlFunc::ThrSendMutex.c_str());
  TQueItf *q = NULL;
  
  while(true) {
    Sleep(500);
    WaitForSingleObject(hMutex,INFINITE);
    GetFromQue();                                           //读取队列

    for(int i=0;i<FLocalDtl->Count;i++){                    //扫描本地列表
      double   curp = 0;
      TLocalDtl *l  = ((TLocalDtl*)FLocalDtl->Items[i]);
      TItfTrd   *it = (TItfTrd *)(FItfTrdLst->Items[l->ItfTrdPos]);
      if(l->SecuID.SubString(1,1).UpperCase() == "S") bourse = bsSZ;
      else bourse = bsSH;

      //10秒查询一次成交情况
      //////////////////////
      undoall = false;
      if((time(NULL) - l->QryTime)>10 || Terminated){
        l->QryTime = time(NULL);

        for(int j=0;j<l->TrdInfo->Count;j++){
          TTrdInfo  *t          = (TTrdInfo *)(l->TrdInfo->Items[j]);
          String    ContractID  = t->ContractID;
          n = 0;
          if(it->QryDetail(ContractID,bourse,p,n,un)<=-1) {continue;}//成交查询 ,出错提示不需要
          curp = n*p;
          if(t->HasUndo){                                  //如果是已经执行撤单的单子
            if(un!=0 || n>=t->Num){                         //如果撤单成功,或者单子已经全部成交
              l->LastPrc  = curp + l->LastPrc;
              l->LastVol += n;
              if(n - t->CurVol>0){
                FRepTime = Time();
                FRepBuy  = true;
                FRepSecuID = l->SecuID;
                FRepVol    = n - t->CurVol;
                FRepPrice  = p;
//                Synchronize(TrdRep);
              }              
              l->CurVol  -= t->CurVol;
              delete t;
              l->TrdInfo->Delete(j);
              j--;
            }
            else{                                          //还未完成撤单
            }
          }
          else if(n - t->CurVol > 0){                                     //加到成交回报
            FRepTime = Time();
            FRepBuy  = false;
            FRepSecuID = l->SecuID;
            FRepVol    = n - t->CurVol;
            FRepPrice  = p;
//            Synchronize(TrdRep);
            l->CurVol += n - t->CurVol;                               //累计该股票所有单子的成交量
            t->CurVol  = n;                                              //保存成交量
          }

          if(l->CurVol + l->LastVol>=l->TotalVol) undoall = true;                   //表示该股票可以全部撤单
        }
        
        q = (TQueItf*)(FInSend->Items[l->Locate]);
        if(q != NULL){
          q->CurVol = l->CurVol + l->LastVol;   //向指针中置当前量
          if(l->CurVol + l->LastVol>0)
            q->AvgPrice = (curp + l->LastPrc)/(l->CurVol + l->LastVol);//向指针中置当前总成交金额
        }
      }
      if(undoall){                                                     //对该股票执行全部撤单
        UndoAllTrd(l);
        if(q!=NULL) q->State = tsFinish;
        FErrMsg = l->SecuID+" 派发完成,派发总量为:"+IntToStr(l->CurVol + l->LastVol);  //派发完成提示
        Synchronize(ShowErr);

        DeleteTrd(i);                                                  //从本地列表中删除
        i--;
        if(!Terminated) continue;
      }

      //按时撤单
      ////////////////////////
//      if((time(NULL) - l->UndoTime) > l->Scheme->TrdCancel*60){
//        l->UndoTime = time(NULL);
//        l->LastTime = time(NULL);

      for(int j=0;j<l->TrdInfo->Count;j++){
        TTrdInfo  *t         = (TTrdInfo *)(l->TrdInfo->Items[j]);
        String    ContractID = t->ContractID;
        bool       canCancel = false;
        if(l->Scheme->TrdCancelTime != 0){
          if((time(NULL) - t->DoTime) > l->Scheme->TrdCancelTime) canCancel=true;        //按时间撤单
        }
        else{
          double zxj = StrToFloat(TRjlSysVar()()->DatDyn->GetField(TRjlSysVar()()->DatDyn->GetLoc(l->SecuID),dtCp))/1000;
          if(zxj<t->Prc - t->Prc*l->Scheme->TrdCancelPrc/100) canCancel=true;           //价偏离撤单
        }
        if(!canCancel) continue;
        
        if(it->Undo(ContractID,bourse)<-1) {
          FErrMsg = "异常错误,按时撤单未成功,合同号:" + ContractID;        //撤单未成功
          Synchronize(ShowErr);
        }
        else{
          t->HasUndo = true;
        }
      }
//        l->CurVol  = 0;

//      if(!Terminated) continue;
//      }
      if(!Terminated){
        //按时下单
        //////////////////////
        if(l->Scheme->TrdSec<0){
          if(l->TrdX==TRjlFunc::StrToDouble(TRjlSysVar()()->DatDyn->GetField(TRjlSysVar()()->DatDyn->GetLoc(l->SecuID),dtCp)))  continue;
          l->TrdX=TRjlFunc::StrToDouble(TRjlSysVar()()->DatDyn->GetField(TRjlSysVar()()->DatDyn->GetLoc(l->SecuID),dtCp));
        }
        else if(l->Scheme->TrdSec>0){                //按指定时间下单
          if((time(NULL) - l->LastTime)<l->Scheme->TrdSec)  continue;
          l->LastTime = time(NULL);
        }
        else{
          if((time(NULL) - l->LastTime)<l->TrdX) continue; //取随机时间下单
          l->TrdX = random(l->Scheme->Sec2-l->Scheme->Sec1)+l->Scheme->Sec1;
        }

        double  prc=0;
        long    vol=0,dv=0;
        String  ContractID="";

        if(GetInfo(l->SecuID) <= -1){
          FErrMsg = "未获得"+ l->SecuID +"的盘口数据";
          Synchronize(ShowErr);
          continue;
        }
        
        if(l->Scheme->ConsignPrice==0)
          prc = FZXJ + l->Scheme->FloatMny;
        else{
          prc = FPrice[l->Scheme->ConsignPrice-1] + l->Scheme->FloatMny;
        }

        if(l->Scheme->VolPercent==0){
          vol = random(l->Scheme->Vol2 - l->Scheme->Vol1) + l->Scheme->Vol1;
        }
        else{
          for(int i=0;i<l->Scheme->VolScheme;i++) vol += FVolum[i];
          vol = vol*l->Scheme->VolPercent/100;
        }
        vol = vol/100<=0?100:vol/100*100;
        
        for(int j=0;j<l->TrdInfo->Count;j++) dv += ((TTrdInfo*)(l->TrdInfo->Items[j]))->Num;
        if(dv+l->LastVol>=l->TotalVol) continue;                 //如果下单的总量已经达到吸纳的总量,就不用再下单了
        if(vol+dv+l->LastVol>l->TotalVol) vol = l->TotalVol - dv - l->LastVol;
                
        int done = -1;
        int balance,avalid,bf,sf;
        if(it->QryStock(l->SecuID,balance,avalid,bf,sf)<=-1){
          FErrMsg = " 股份查询失败,"+l->SecuID + "价格"+FloatToStr(prc) + " 派发下单未成功";
          Synchronize(ShowErr);
          continue;
        }
        else{
          if(vol>balance){
            vol = balance;
            FErrMsg = " 派发股份不足";
            Synchronize(ShowErr);
            continue;
          }
        }
        if((l->PriceLimit==0 && l->VolLimit == 0) || (prc>l->PriceLimit && vol<l->VolLimit))
          done = it->Sell(l->SecuID,prc,vol,ContractID);

        if(done <= -1) {
          FErrMsg = "股票"+l->SecuID + "价格"+FloatToStr(prc) + " 吸纳下单未成功";
          Synchronize(ShowErr);
          continue;
        }
        else AddTrd(l,ContractID,vol,prc);
      }

    } //end for

    if(FLocalDtl->Count>0) ReleaseSemaphore(hMutex,1,NULL);
    
    if(Terminated){                                           //线程中断全撤单
      for(int i=0;i<FLocalDtl->Count;i++){
        TLocalDtl *l = ((TLocalDtl*)FLocalDtl->Items[i]);
        UndoAllTrd(l);
      }
      break;
    }
  }

  CloseHandle(hMutex);
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
    DWORD numRead;
    DWORD numToWrite;

    if (argc != 2)
    {
        HANDLE namedPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            1024, 1024,
            NMPWAIT_USE_DEFAULT_WAIT,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            cout << "Can't create pipe. Error. Press any key to exit " << GetLastError();
            _getch();
            exit(0);
        }

        HANDLE serverSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("clientSemaphore"));

        MyProcess *clientProcess = new MyProcess(argv[0]);

        ConnectNamedPipe(namedPipe, NULL);

        WaitForSingleObject(serverSemaphore, INFINITE);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Server process\n");

        if (!WriteFile(namedPipe, "Ready", 1024, &numToWrite, NULL))
            return 0;

        while (1)
        {
            ReleaseSemaphore(clientSemaphore, 1, NULL);
            WaitForSingleObject(serverSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
                printf("Client message: %s", buffer);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);
                free(buffer);
                return 0;
            }

            printf("\nInput message to client: ");
            fflush(stdin);
            gets_s(buffer, 1024);

            if (!WriteFile(namedPipe, buffer, 1024, &numToWrite, NULL))
                break;

            ReleaseSemaphore(clientSemaphore, 1, NULL);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);

                free(buffer);
                return 0;
            }
        }
        return 0;
    }
    else
    {
        HANDLE serverSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("clientSemaphore"));

        HANDLE namedPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            printf("Can't create pipe. Error. Press any key to exit", GetLastError());
            _getch();
            exit(0);
        }

        ReleaseSemaphore(serverSemaphore, 1, NULL);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Client process\n");

        while (1)
        {
            WaitForSingleObject(clientSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
            {
                if (!strcmp(buffer, "exit"))
                {
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }

                printf("Server message: %s", buffer);

                char input[1024] = { '\0' };
                cout << "\nInput message to server: ";
                fflush(stdin);
                gets_s(input, 1024);

                if (!WriteFile(namedPipe, input, 1024, &numToWrite, NULL))
                    break;

                if (!strcmp(input, "exit"))
                {
                    ReleaseSemaphore(serverSemaphore, 1, NULL);
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }
            }
            ReleaseSemaphore(serverSemaphore, 1, NULL);
        }
        return 0;
    }

#elif __linux__
    pid_t pid;
    key_t key = ftok("/home/", 0);

    struct sembuf serverSemaphore;
    struct sembuf clientSemaphore;
    int semaphoreId;

    int sharedMemoryId;
    char *segmentPtr;

    if (argc != 2)
    {
        switch (pid = fork())
        {
        case -1:
            printf("Can't fork process %d\n", pid);
            break;
        case 0:
            execlp("gnome-terminal", "gnome-terminal", "-x", argv[0], "1", NULL);
        default:
            if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
            {
                if ((sharedMemoryId = shmget(key, 1024, 0)) == -1)
                {
                    printf("error\n");
                    exit(1);
                }
            }

            if ((segmentPtr = (char*)shmat(sharedMemoryId, NULL, 0)) == (char*)(-1))
            {
                printf("Can't attach shared memory\n");
                exit(1);
            }

            semaphoreId = semget(key, 1, 0666 | IPC_CREAT);

            if (semaphoreId < 0)
            {
                printf("Can't get semaphore\n");
                exit(EXIT_FAILURE);
            }

            if (semctl(semaphoreId, 0, SETVAL, (int)0) < 0)
            {
                printf("Can't initialize semaphore\n");
                exit(EXIT_FAILURE);
            }

            serverSemaphore.sem_num = 0;
            serverSemaphore.sem_op = 0;
            serverSemaphore.sem_flg = 0;

            printf("Server process: ");

            while (1) {
                char *message = NULL;
                message = (char*)malloc(1024 * sizeof(char));

                semop(semaphoreId, &serverSemaphore, 1);

                printf("\nInput message to client: ");
                fflush(stdin);
                cin >> message;

                strcpy(segmentPtr, message);

                serverSemaphore.sem_op = 3;
                semop(semaphoreId, &serverSemaphore, 1);

                serverSemaphore.sem_op = 0;
                semop(semaphoreId, &serverSemaphore, 1);

                if (!strcmp("exit", message))
                    return 0;

                strcpy(message, segmentPtr);
                printf("Client message: %s\n", message);
            }
            return 0;
        }
    }
    else
    {
        if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
Ejemplo n.º 26
0
Archivo: semop.c Proyecto: nawhizz/KAIT
int
SemOp(int semid, struct sembuf *semopbuf, DWORD procid, int piid, IPCT *ipct)
{
	int	i;
	BOOL	ret;
	DWORD	dwret;
	HANDLE	hsem;
#ifndef	TERMINAL_SERVICE
	char	semstr[16];
#else
	char	semstr[30];
#endif	/* TERMINAL_SERVICE */

#ifndef	TERMINAL_SERVICE
	MakeSemstr(semstr, semopbuf->sem_num, semid, ipct->semt[semid].key);
#else
	OSVERSIONINFOEX osvi;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

	if( !GetVersionEx ((OSVERSIONINFO *) &osvi) )
	{
	  // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		GetVersionEx( (OSVERSIONINFO *) &osvi );
	}

	if( osvi.dwMajorVersion >= 5 )	/* Windows 2000 */
		MakeGlobalSemstr(semstr, semopbuf->sem_num, semid, ipct->semt[semid].key);
	else
		MakeSemstr(semstr, semopbuf->sem_num, semid, ipct->semt[semid].key);
#endif	/* TERMINAL_SERVICE */
	hsem=OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, semstr);
	if (hsem==NULL)
	{
		errno=GetLastError();

		return -1;
	}

	if (semopbuf->sem_op<0)
	{
		if (ipct->semb[semid][semopbuf->sem_num].semval
			>= abs((int)semopbuf->sem_op))
			ipct->semb[semid][semopbuf->sem_num].semncnt++;

		if (ipct->semb[semid][semopbuf->sem_num].semval
			< abs((int)semopbuf->sem_op))
		{
			if (semopbuf->sem_flg & IPC_NOWAIT)
			{
				ipct->semb[semid][semopbuf->sem_num].sempid=procid;
				CloseHandle(hsem);
				return 0;
			}
		}

		for (i=0; i<abs((int)semopbuf->sem_op); i++)
		{
/**************
			do
			{
				dwret=MsgWaitForMultipleObjects(1, &hsem, 
					FALSE, INFINITE, 
					QS_SENDMESSAGE|QS_POSTMESSAGE|QS_TIMER);
***************/
			dwret=WaitForSingleObject(hsem, INFINITE);
			switch (dwret)
			{
/*****************
			case	WAIT_OBJECT_0 + 1 :
				if (l_peekmessage()<0)
				{
					CloseHandle(hsem);
					return -1;
				}
				break;
*****************/

			case	WAIT_OBJECT_0	:
/* by KJC 98.09.24 **************************************
				ipct->semb[semid][semopbuf->sem_num].semval--;
***********************************************************/
				InterlockedDecrement(&ipct->semb[semid][semopbuf->sem_num].semval);
/***********************************************************/
				break;
			case	WAIT_TIMEOUT	:
			case	WAIT_FAILED	:
				errno=GetLastError();
			default	:
				CloseHandle(hsem);
				return -1;
			}
/***************
			} while (dwret==(WAIT_OBJECT_0 + 1));
***************/

			if (semopbuf->sem_flg & SEM_UNDO)
			{
				ipct->pseminfo[piid].semadj[semid][semopbuf->sem_num]++;
			}
		}

		ipct->semb[semid][semopbuf->sem_num].sempid=procid;
		ipct->semb[semid][semopbuf->sem_num].semncnt--;
	//	CloseHandle(hsem);
	}
	else if (semopbuf->sem_op>0)
	{
		ret=ReleaseSemaphore(hsem, semopbuf->sem_op, NULL);
		if (ret==FALSE)
		{

			CloseHandle(hsem);
			return -1;
		}
		ipct->semb[semid][semopbuf->sem_num].sempid=procid;
/* by KJC 98.9.24 ********************************
		ipct->semb[semid][semopbuf->sem_num].semval+=(int)semopbuf->sem_op;
***********************************************************/
		InterlockedExchangeAdd(&ipct->semb[semid][semopbuf->sem_num].semval, (long)semopbuf->sem_op);
/***********************************************************/
	//	CloseHandle(hsem);

		if (semopbuf->sem_flg & SEM_UNDO)
		{
			ipct->pseminfo[piid].semadj[semid][semopbuf->sem_num]-=(int)semopbuf->sem_op;
		}

	}
	else
	{
		if (!ipct->semb[semid][semopbuf->sem_num].semval)
		{
			CloseHandle(hsem);
			return 0;
		}

		if (semopbuf->sem_flg & IPC_NOWAIT)
		{
			CloseHandle(hsem);
			return 0;
		}

		ipct->semb[semid][semopbuf->sem_num].sempid=procid;
		ipct->semb[semid][semopbuf->sem_num].semzcnt++;
		/*###################################*/
		/*###################################*/

	}
	
	CloseHandle(hsem);
	return 0;
}
Ejemplo n.º 27
0
static os_result
condTimedWait(
    os_cond *cond,
    os_mutex *mutex,
    DWORD timeout)
{
    HANDLE hQueue;
    HANDLE hMtx;
    char name[OS_SERVICE_ENTITY_NAME_MAX];
    DWORD wsr;
    LONG c;
    LONG lockCount;
    os_result osr;
    os_result result;

    assert(cond != NULL);
    assert(mutex != NULL);

    result = os_resultSuccess;
    if (cond->scope == OS_SCOPE_SHARED) {
        _snprintf(name, sizeof(name), "%s%s%d%d",
            (os_sharedMemIsGlobal() ? OS_SERVICE_GLOBAL_NAME_PREFIX : ""),
            OS_SERVICE_SEM_NAME_PREFIX,
            cond->qId,
            os_getShmBaseAddressFromPointer(cond));

        hQueue = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, name);
        if (hQueue == NULL) {
            OS_DEBUG_1("condTimedWait", "OpenSemaphore failed %d", (int)GetLastError());
            assert(0);
            return os_resultFail;
        }

        _snprintf(name, sizeof(name), "%s%s%d%d",
            (os_sharedMemIsGlobal() ? OS_SERVICE_GLOBAL_NAME_PREFIX : ""),
            OS_SERVICE_EVENT_NAME_PREFIX,
            mutex->id,
            os_getShmBaseAddressFromPointer(cond));
        hMtx = OpenEvent(EVENT_ALL_ACCESS, FALSE, name);
        if (hMtx == NULL) {
            OS_DEBUG_1("condTimedWait", "OpenEvent failed %d", (int)GetLastError());
            CloseHandle(hQueue);
            assert(0);
            return os_resultFail;
        }
    } else {
        hQueue  = (HANDLE)cond->qId;
        hMtx  = (HANDLE)mutex->id;
    }

    InterlockedIncrement(&cond->state);
    lockCount = InterlockedDecrement(&mutex->lockCount);
    if (lockCount > 0) {
        wsr = SignalObjectAndWait(hMtx, hQueue, timeout, FALSE);
    } else {
        wsr = WaitForSingleObject(hQueue, timeout);
    }
    assert((wsr == WAIT_OBJECT_0) || (wsr == WAIT_FAILED) || (wsr == WAIT_ABANDONED) || (wsr == WAIT_TIMEOUT));
    if (wsr == WAIT_TIMEOUT) {
        result = os_resultTimeout;
    } else if (wsr != WAIT_OBJECT_0) {
        result = os_resultFail;
    }

    c = InterlockedDecrement(&cond->state);
    osr = os_mutexLock(mutex);
    if (osr != os_resultSuccess) {
        result = osr;
    }
    if (cond->scope == OS_SCOPE_SHARED) {
        CloseHandle(hQueue);
        CloseHandle(hMtx);
    }

    return result;
}
bool CanalSharedMemLevel1::doCmdOpen( const char *szInterface, unsigned long flags )
{
    HANDLE hMapListen = NULL;
    HANDLE hListenMutex = NULL;
    HANDLE semListenCommand = NULL;
    HANDLE semListenDone = NULL;
    DWORD err;

    bool rv = true;	// return value
    wxChar buf[ MAX_PATH ];
    struct __shmOpen *pListenShMemArea = NULL;


    ::wxLogDebug( _T("CanalSharedMemLevel1: Before %ul"), GetLastError() );
    SetLastError( 0 );


    if ( NULL == ( semListenCommand =
                       OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                      FALSE,
                                      CANAL_LISTEN_COMMAND_SEM ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Command semaphore %ul"),
                      ( err = GetLastError() ) );
        return false;
    }


    if ( NULL == ( semListenDone =
                       OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                      FALSE,
                                      CANAL_LISTEN_DONE_SEM ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Done semaphore %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( semListenCommand );
        return false;
    }

    // Get client shared memory
    if ( NULL == ( hMapListen =
                       OpenFileMapping( FILE_MAP_WRITE,
                                        TRUE,
                                        CANAL_LISTEN_SHM_NAME ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Command semaphore %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    if ( NULL == ( pListenShMemArea =
                       (struct __shmOpen *)MapViewOfFile( hMapListen,
                               FILE_MAP_WRITE, 0, 0, 0 ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Shared memory %ul"),
                      ( err = GetLastError() ) );
        CloseHandle( hMapListen );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    if ( NULL == ( hListenMutex =
                       OpenMutex( MUTEX_ALL_ACCESS,
                                  TRUE,
                                  CANAL_LISTEN_SHARED_MEMORY_MUTEX ) ) ) {

        ::wxLogDebug( _T("CanalSharedMemLevel1: Failed to open Listen Nutex %ul"),
                      GetLastError() );
        UnmapViewOfFile( pListenShMemArea );
        CloseHandle( hMapListen );
        CloseHandle( semListenCommand );
        CloseHandle( semListenDone );
        return false;
    }

    // Get access to Listenthread common resources
    WaitForSingleObject( hListenMutex, INFINITE );

    // Write Command
    pListenShMemArea->m_command = CANAL_COMMAND_OPEN_VSCP_LEVEL1;
    pListenShMemArea->m_flags = flags;
    if ( NULL != szInterface ) {
        strncpy( pListenShMemArea->m_strIfName, szInterface, sizeof( szInterface ) );
    }

    // Execute command on server
    ReleaseSemaphore( semListenCommand, 1, NULL );

    // Wait until command is handled
    WaitForSingleObject( semListenDone, INFINITE );

    if ( !pListenShMemArea->m_cmdResult ) {

        // Give the server thread some time to start
        Sleep( 1 );

        // Get the client command memory area
        _stprintf( buf, CANAL_LISTEN_CLIENT_SHM_TEMPLATE, pListenShMemArea->m_shmid );
        if ( NULL != ( m_hMapClient =
                           OpenFileMapping( FILE_MAP_WRITE, TRUE, buf ) ) ) {

            if ( NULL != ( m_pCommandMem = MapViewOfFile( m_hMapClient,
                                           FILE_MAP_WRITE, 0, 0, 0 ) ) ) {

                // Save a pointer to the command structure
                m_pLevel1 = (struct __shmCanalLevelI *)m_pCommandMem;

                // Wait for server thread to give clearence
                DWORD start = GetTickCount();
                while( 0xaa55 != m_pLevel1->m_test ) {
                    if ( ( GetTickCount() - start ) > 1000 ) {

                        // Release listen thread resources we are done with them

                        // No need for memory anymore
#ifndef CANAL_MFCAPP
                        wxLogDebug(_T("ERROR: No server thread\n"));
#endif
                        return false;
                    }
                }

                // Get the Client Semaphores
                _stprintf( buf, CANAL_CLIENT_COMMAND_SEM_TEMPLATE, pListenShMemArea->m_shmid );
                if ( NULL == ( m_semClientCommand = OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                                    TRUE,
                                                    buf ) ) ) {
                    CloseHandle( semListenCommand );
                    return false;
                }

                _stprintf( buf, CANAL_CLIENT_DONE_SEM_TEMPLATE, pListenShMemArea->m_shmid );
                if ( NULL == ( m_semClientDone = OpenSemaphore( SEMAPHORE_ALL_ACCESS,
                                                 TRUE,
                                                 buf ) ) ) {
                    CloseHandle( semListenCommand );
                    return false;
                }

                // Go on
                m_pLevel1->m_test = 0x55aa;

                // We have an open channel!
                // Do a dummy Open of interface
                doCommand( CANAL_COMMAND_OPEN );

            }
            else {

                // Failed to map in client shared memory

            }

        }
        else {

            // Failed to get Client shared memory

        }

    }

    // Release listen thread resources we are done with them
    ReleaseMutex( hListenMutex );

    if ( NULL != semListenCommand ) {
        CloseHandle( semListenCommand );
    }

    if ( NULL != semListenDone ) {
        CloseHandle( semListenDone );
    }

    // release listthread sh memory
    if ( NULL != pListenShMemArea ) {
        UnmapViewOfFile( pListenShMemArea );
    }

    // ...and handle for shared memory
    if ( NULL != hMapListen ) {
        CloseHandle( hMapListen );
    }

    return rv;
}
Ejemplo n.º 29
0
int RGServerPort :: Connect (RGClient* parent) {

	if (Connected) {

		LastError = RGALREADYCONNECTED;
		return -1;
	}

	if (parent == NULL) {

		LastError = RGCLIENTNULL;
		return -1;
	}
	
	Parent = parent;

	//
	//  Name is the name of the server.  To get the client name, use Parent.
	//

	RGString OKToReadName = Name + "OKToReadReceiveBuffer";
	RGString OKToWriteName = Name + "OKToWriteIntoReceiveBuffer";
	RGString ContinuationName = Name + "ReceiveContinuation";
	RGString ImTryingToContactYouName = Name + "ImTryingToContactYou";
	RGString BufferName = Name + "ReceiveBuffer";
	RGString To ("To");
	RGString HotLineName = "HotLineFrom" + Name + To + Parent->GetName ();

	FirstTime = TRUE;
	LastError = RGOK;

//	BufferHandle = OpenFileMapping (PAGE_READWRITE, FALSE, BufferName);

	BufferHandle = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
                4, BufferName);
	
	if (BufferHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}
	
	BufferMapAddress = (unsigned char*)MapViewOfFile (BufferHandle, 
		FILE_MAP_WRITE, 0, 0, 0);
	
	if (BufferMapAddress == NULL) {
		
		cout << "Map Error = " << GetLastError () << endl;
		LastError = RGNOBUFFER;
		return -1;
	}

	int LongLength = sizeof (unsigned long);

	unsigned long* size = (unsigned long*) BufferMapAddress;
	Type = (unsigned long*) (BufferMapAddress + LongLength);
	Length = (unsigned long*) (BufferMapAddress + 2 * LongLength);
	ReplyPointer = (unsigned long*) (BufferMapAddress + 3 * LongLength);
	ServerPid = (unsigned long*) (BufferMapAddress + 4 * LongLength);
	BufferSize = *size;
	DataBegin = BufferMapAddress + DATAMAPOFFSET;
	
	OKToReadHandle = OpenEvent (EVENT_ALL_ACCESS, FALSE, OKToReadName);
	
	if (OKToReadHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}

	OKToWriteHandle = OpenEvent (EVENT_ALL_ACCESS, FALSE, OKToWriteName);
	
	if (OKToWriteHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}

	ContinuationHandle = OpenEvent (EVENT_ALL_ACCESS, FALSE, ContinuationName);
	
	if (ContinuationHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}

	ImTryingToContactYouHandle = OpenSemaphore (SEMAPHORE_ALL_ACCESS, FALSE, ImTryingToContactYouName);
	
	if (ImTryingToContactYouHandle == NULL) {
		
		cout << "Windows error:  " << GetLastError () << endl;
		LastError = RGNOHANDLE;
		return -1;
	}

	ServerPidHandle = OpenProcess (SYNCHRONIZE, FALSE, *ServerPid);  // SYNCHRONIZE	required by "wait" functions

	if (ServerPidHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}

	HotLineHandle = CreateEvent (NULL, FALSE, FALSE, HotLineName);
	
	if (HotLineHandle == NULL) {
		
		LastError = RGNOHANDLE;
		return -1;
	}
	
	Connected = TRUE;
	return 0;
}
Ejemplo n.º 30
0
HSemaphore::HSemaphore( const GChar * strName, ThreadingAccess iAccessFlags ):
    HThreadingObject()
{
    m_hThreadingObject = OpenSemaphore( _BuildThreadingAccess(iAccessFlags), FALSE, strName );
    DebugAssert( m_hThreadingObject != NULL );
}