void jumpMessageQueueCreate(JUMPPlatformCString type, JUMPMessageQueueStatusCode* code){ char mailslotName[100]; HANDLE hSlot = mailslotGet(type, NULL); generateMailslotName(type, mailslotName, GetCurrentProcessId()); if (JUMP_WIN_DEBUG) { printf("jumpMessageQueueCreate: Mailslot name=%s\n", mailslotName); } if (hSlot!= NULL) { printf("Warning: jumpMessageQueueCreate - MessageQueue already exists for process \n"); *code = JUMP_MQ_FAILURE; return; } hSlot = CreateMailslot(mailslotName, 0, MAILSLOT_WAIT_FOREVER, NULL); if (hSlot == INVALID_HANDLE_VALUE) { printf("ERROR: jumpCreateMailslot failed with %d\n", GetLastError()); *code = JUMP_MQ_FAILURE; return; } else { if (JUMP_WIN_DEBUG) { printf("jumpCreateMailslot: Mailsot created successfully.\n"); } } mailslotAdd(type, hSlot); *code = JUMP_MQ_SUCCESS; }
// // Function: ServeMailslot // // Description: // This function is the mailslot server worker function to process all // incoming mailslot I/O. // DWORD WINAPI ServeMailslot(LPVOID lpParameter) { char buffer[2048]; DWORD NumberOfBytesRead; DWORD Ret; HANDLE Mailslot; if ((Mailslot = CreateMailslot("\\\\.\\mailslot\\myslot", 2048, MAILSLOT_WAIT_FOREVER, NULL)) == INVALID_HANDLE_VALUE) { printf("Failed to create a MailSlot %d\n", GetLastError()); return 0; } while((Ret = ReadFile(Mailslot, buffer, 2048, &NumberOfBytesRead, NULL)) != 0) { if (StopProcessing) break; printf("Received %d bytes\n", NumberOfBytesRead); } CloseHandle(Mailslot); return 0; }
int read_slot(const char *mailslotname) { HANDLE h; DWORD nr; char data[30000]; DWORD nextsize, nummsg = 0; if (strncmp(mailslotname, "\\\\.\\mailslot\\", 13) && strncmp(mailslotname, "\\\\*\\mailslot\\", 13)) { printf("Must specify local mailslot name (starting with \\\\.\\mailslot\\)\n"); return 1; } h = CreateMailslot(mailslotname, 0, MAILSLOT_WAIT_FOREVER, NULL); if (h == INVALID_HANDLE_VALUE) { printf("Unable to create mailslot %s: %d\n", mailslotname, GetLastError()); return 1; } if (!ReadFile(h, data, sizeof(data)-1, &nr, NULL)) { printf("Error reading: %d\n", GetLastError()); return 1; } data[nr] = '\0'; printf("%s\n", data); CloseHandle(h); }
bool TUI::OnCreate(TD3DWindow* w, TPanel* p) { // create base class EDevice.InitTimer(); m_D3DWindow = w; m_D3DPanel = p; VERIFY(m_D3DWindow); EDevice.Initialize(); // Creation ETOOLS::ray_options (CDB::OPT_ONLYNEAREST | CDB::OPT_CULL); pInput = xr_new<CInput>(FALSE,mouse_device_key); UI->IR_Capture (); m_bReady = true; if (!CreateMailslot()){ ELog.DlgMsg (mtError,"Can't create mail slot.\nIt's possible two Editors started."); return false; } if (!FS.path_exist(_local_root_)){ ELog.DlgMsg (mtError,"Undefined Editor local directory."); return false; } BeginEState (esEditScene); return true; }
HANDLE mailslotCreate (char *name) { /* Creates a mailslot with the specified name and returns the handle */ /* Should be able to handle a messages of any size */ return CreateMailslot(name, 0, // no maximum message size MAILSLOT_WAIT_FOREVER, // no time-out for operations (LPSECURITY_ATTRIBUTES)NULL); // default security }
void msCreate(LPCSTR name) { string256 fn; xr_sprintf(fn, sizeof(fn), "\\\\.\\mailslot\\%s", name); hLocalSlot = CreateMailslot( fn, 0, // no maximum message size MAILSLOT_WAIT_FOREVER, // no time-out for operations (LPSECURITY_ATTRIBUTES)NULL); // no security attributes if (hLocalSlot == INVALID_HANDLE_VALUE) return; // Msg ("* mailSLOT successfully created."); }
HANDLE Mailslot_create(const char* name) { HANDLE handle; char slotname[100]; strcpy_s(slotname, 100, "\\\\.\\mailslot\\"); strcat_s(slotname, 100, name); handle = CreateMailslot( (LPCTSTR) slotname, (DWORD) 0, (DWORD) MAILSLOT_WAIT_FOREVER, (LPSECURITY_ATTRIBUTES) NULL ); return handle; }
int StartInstanceComms(void) { DWORD id; HANDLE hMailSlot = CreateMailslot(lpszSlotName, 0, /* no maximum message size */ MAILSLOT_WAIT_FOREVER, /* no time-out for read operations */ (LPSECURITY_ATTRIBUTES) NULL); /* no security attributes */ if (hMailSlot == INVALID_HANDLE_VALUE) { return FALSE; } ghMailSlot = hMailSlot; CloseHandle(CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)msThread, (LPVOID)hMailSlot, 0, &id)); return TRUE; }
void main(void) { HANDLE Mailslot; char buffer[256]; DWORD NumberOfBytesRead; // Create the mailslot if ((Mailslot = CreateMailslot("\\\\.\\mailslot\\myslot", 0, MAILSLOT_WAIT_FOREVER, NULL)) == INVALID_HANDLE_VALUE) { printf("Failed to create a MailSlot %d\n", GetLastError()); return; } // Read data from the mailslot forever! while(ReadFile(Mailslot, buffer, 256, &NumberOfBytesRead, NULL) != 0) { printf("%.*s\n", NumberOfBytesRead, buffer); } }
HANDLE mailslotCreate(char *name) { /* Creates a mailslot with the specified name and returns the handle */ /* Should be able to handle a messages of any size */ HANDLE newMailSlot; newMailSlot = CreateMailslot( name, 0, TIME_OUT, (LPSECURITY_ATTRIBUTES)NULL); if (newMailSlot == INVALID_HANDLE_VALUE) { printf("CreateMailslot failed with %d\n", GetLastError()); return FALSE; } else printf("Mailslot created successfully.\n"); return newMailSlot; }
void MailWork() { HANDLE hMalilist = CreateMailslot(MAILLISTNAME, 0, MAILSLOT_WAIT_FOREVER, NULL); if (INVALID_HANDLE_VALUE == hMalilist) { std::cout<<"create mail fail"<<std::endl; return ; } TCHAR szRead[MAX_PATH] = {0}; DWORD dwReadSize = 0; BOOL bRead = ReadFile(hMalilist, szRead, MAX_PATH, &dwReadSize, NULL); if (bRead) { std::wcout<<_T("read text:")<<szRead<<std::endl; } else { std::wcout<<_T("read fail")<<std::endl; } CloseHandle(hMalilist); return ; }
int main(int argc, char * argv[]) { int i; double lossRate; TCHAR temp[STR_SIZE]; //used for conversion from char to TCHAR whenever is needed char tempChar[STR_SIZE]; HANDLE hFileMailBoxOut[NUM_ROPE_PMF];/*handles for mail boxes so that we can communicate with child proesses*/ HANDLE hFileMailBoxIn[NUM_ROPE_PMF]; STARTUPINFO si[NUM_ROPE_PMF]; PROCESS_INFORMATION pi[NUM_ROPE_PMF]; char ropePMFConfigFiles[NUM_ROPE_PMF][STR_SIZE]; char sharedMemNames[NUM_ROPE_PMF][STR_SIZE]; char mailBoxNamesOut[NUM_ROPE_PMF][STR_SIZE]; char mailBoxNamesIn[NUM_ROPE_PMF][STR_SIZE]; char VSconfigFileName[STR_SIZE]; char cmdLine[NUM_ROPE_PMF][STR_SIZE]; char cmdLineVS[STR_SIZE]; FILE *configFile; int frameCounter=0; if(argc!=3) { printf("oldesv.exe [configFile] [lossRAte]"); return -1; } /*get the loss rate*/ lossRate = atof(argv[2]); /*open the config file for reading*/ configFile = fopen(argv[1],"rt"); if(!configFile) { printf("Error opening config file %s\n",argv[1]); return -1; } /*get the config file names*/ for(i=0; i<NUM_ROPE_PMF; i++) { fgets(ropePMFConfigFiles[i], STR_SIZE, configFile); removeCR(ropePMFConfigFiles[i], STR_SIZE); } /*get the share memory names*/ for(i=0; i<NUM_ROPE_PMF; i++) { fgets(sharedMemNames[i], STR_SIZE, configFile); removeCR(sharedMemNames[i], STR_SIZE); } /*get the mail box names*/ for(i=0; i<NUM_ROPE_PMF; i++) { fgets(mailBoxNamesOut[i], STR_SIZE, configFile); removeCR(mailBoxNamesOut[i], STR_SIZE); sprintf(tempChar, "\\\\.\\mailslot\\%s", mailBoxNamesOut[i]); sprintf(mailBoxNamesOut[i], "%s", tempChar); fgets(mailBoxNamesIn[i], STR_SIZE, configFile); removeCR(mailBoxNamesIn[i], STR_SIZE); sprintf(tempChar, "\\\\.\\mailslot\\%s", mailBoxNamesIn[i]); sprintf(mailBoxNamesIn[i], "%s", tempChar); } /*get the VS config file name*/ fgets(VSconfigFileName, STR_SIZE, configFile); removeCR(VSconfigFileName, STR_SIZE); /*close the config file*/ fclose(configFile); /*create the incoming mail boxes first before launching the child processes*/ for(i=0; i<NUM_ROPE_PMF; i++) { /*create the incoming mail boxes*/ charToTCHAR(temp, mailBoxNamesIn[i]); printf("Main process(%d): incoming mail box:%s\n",GetCurrentProcessId(),mailBoxNamesIn[i]);//debug hFileMailBoxIn[i] = CreateMailslot(temp, 0, // no maximum message size MAILSLOT_WAIT_FOREVER, // no time-out for operations (LPSECURITY_ATTRIBUTES) NULL); // default security if (hFileMailBoxIn[i] == INVALID_HANDLE_VALUE) { printf("CreateMailslot failed with %d\n", GetLastError()); return -1; } } /*get the command line ready*/ for(i=0; i<NUM_ROPE_PMF; i++) { /*the first two encoders are for the texture*/ if(i<=1) { sprintf(cmdLine[i],"lencod_t.exe -f %s %f %s %s %s", ropePMFConfigFiles[i], lossRate, sharedMemNames[i], mailBoxNamesOut[i], mailBoxNamesIn[i]); } else { sprintf(cmdLine[i],"lencod_d.exe -f %s %f %s %s %s", ropePMFConfigFiles[i], lossRate, sharedMemNames[i], mailBoxNamesOut[i], mailBoxNamesIn[i]); } } /*launch the processes*/ for(i=0; i<NUM_ROPE_PMF; i++) { ZeroMemory( &si[i], sizeof(si[i]) ); si[i].cb = sizeof(si[i]); ZeroMemory( &pi[i], sizeof(pi[i]) ); charToTCHAR(temp, cmdLine[i]); // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) temp, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si[i], // Pointer to STARTUPINFO structure &pi[i] ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d).\n", GetLastError() ); return -1; } } printf("Main process(%d): child processes launched\n",GetCurrentProcessId()); /*give it some time for the child processes to create the mail boxes*/ Sleep(6000); for(i=0; i<NUM_ROPE_PMF; i++) { /*create the outgoing mail boxes*/ charToTCHAR(temp, mailBoxNamesOut[i]); printf("Main process(%d): outgoing mail box:%s\n",GetCurrentProcessId(),mailBoxNamesOut[i]);//debug hFileMailBoxOut[i] = CreateFile(temp, GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL); if (hFileMailBoxOut[i] == INVALID_HANDLE_VALUE) { printf("CreateFile failed with %d.\n", GetLastError()); return -1; } } printf("Main process(%d): outgoing mail boxes linked\n",GetCurrentProcessId()); /*main task loop*/ while(1) { int frameFinishFlag=0; int sequenceFinishFlag=0; int message; //Sleep(5000);//debug //printf("Main process(%d): child processes kicked wait for 5 seconds and then start checking for return messages........\n",GetCurrentProcessId());//debug //printf("\nPress enter for next frame\n");//debug //getchar();//debug /*kick the child processes going*/ message = MSG_START_FRAME; for(i=0; i<NUM_ROPE_PMF; i++) { msgSend(hFileMailBoxOut[i], &message, sizeof(int)); } /*get responses from the child processes*/ while(1) { for(i=0; i<NUM_ROPE_PMF; i++) { message = msgRead(hFileMailBoxIn[i]); if(message==MSG_FRAME_FINISHED) { frameFinishFlag++; } else if(message==MSG_SEQUENCE_FINISHED) { sequenceFinishFlag++; } else if(message==MSG_NO_MESSAGE) { } else { printf("Unexpected message\n"); exit(0); } } /*if all child processes have finished then we exit otherwise we wait for 200ms and then check again*/ if((frameFinishFlag==NUM_ROPE_PMF) || (sequenceFinishFlag==NUM_ROPE_PMF)) { printf("Main process(%d): frame finish or sequence finish\n",GetCurrentProcessId());//debug break; } Sleep(200); } if(sequenceFinishFlag==NUM_ROPE_PMF) { printf("Main process(%d): sequence finish\n",GetCurrentProcessId());//debug break; } else { int ret; /*view synthesizer can be launched using a blocking system call*/ /*view synthesizer just need to run for a single frame*/ sprintf(cmdLineVS,"ViewSynVC8d.exe %s %d %s %s %s %s", VSconfigFileName, frameCounter, sharedMemNames[0], sharedMemNames[1], sharedMemNames[2], sharedMemNames[3]); ret = system(cmdLineVS); if(ret!=0) { printf("Error lanching the view synthesizer\n"); exit(0); } /*open the distortion file and save the distortion*/ frameDistortionFile = fopen("singleFrameDistortionFile.bin","rb"); if(frameDistortionFile == NULL) { printf("Error opening distortion file\n"); exit(0); } fread(&frameDistortion[frameCounter],sizeof(double),1,frameDistortionFile); fclose(frameDistortionFile); } frameCounter++; } /*wait until the child processes finish*/ for(i=0; i<NUM_ROPE_PMF; i++) { // Wait until child process exits. WaitForSingleObject( pi[i].hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi[i].hProcess ); CloseHandle( pi[i].hThread ); } printf("Main process(%d): Child processes finished\n",GetCurrentProcessId()); /*close the handles for the mail boxes*/ for(i=0; i<NUM_ROPE_PMF; i++) { CloseHandle(hFileMailBoxOut[i]); CloseHandle(hFileMailBoxIn[i]); } printf("Main process(%d): mail boxes closed\n",GetCurrentProcessId()); /*print the distortions*/ for(i=0; i<frameCounter; i++) { printf("Frame:%d distortion:%f\n",i,frameDistortion[i]); } return 0; }
DWORD WINAPI MailslotThread(LPVOID pData) { HANDLE hSlot; // Handle for the Mailslot hSlot = CreateMailslot(NIFTYKB_MAILSLOT_PATH, 0, // no max msg size MAILSLOT_WAIT_FOREVER, (LPSECURITY_ATTRIBUTES)NULL); // default security if (hSlot == INVALID_HANDLE_VALUE) { ts3Functions.logMessage("Failed CreateMailslot", LogLevel_ERROR, "NiftyKb Plugin", 0); return PLUGIN_ERROR_CREATESLOT_FAILED; } ts3Functions.logMessage("Mailslot Created", LogLevel_INFO, "NiftyKb Plugin", 0); // While the plugin is running while (pluginRunning) { //DWORD timerWait = MsgWaitForMultipleObjects(1, &hPttDelayTimer, FALSE, PLUGIN_THREAD_TIMEOUT, QS_ALLINPUT); //if (timerWait == WAIT_FAILED) { // break; //} //if (timerWait == WAIT_OBJECT_0) { // PTTDelayCallback(NULL, 0, 0); //} DWORD messageSize, messageCount, messageBytesRead; char *messageStr, *arg; DWORD messageTimeout = PLUGIN_THREAD_TIMEOUT; BOOL ok; ok = GetMailslotInfo(hSlot, (LPDWORD)NULL, // No max size &messageSize, &messageCount, (LPDWORD)NULL); //&messageTimeout); if (!ok) { DWORD err = GetLastError(); if (err == WAIT_TIMEOUT) { continue; } ts3Functions.logMessage("Failed GetMailslotInfo", LogLevel_ERROR, "NiftyKb Plugin", 0); return PLUGIN_ERROR_READ_FAILED; } if (messageSize == MAILSLOT_NO_MESSAGE) { ::SleepEx(5, TRUE); // allow timers to fire continue; } // Retrieve message messageStr = (LPTSTR)malloc(messageSize + 1); ok = ReadFile(hSlot, messageStr, messageSize, &messageBytesRead, NULL); // not overlapped i/o if (!ok || messageBytesRead == 0) { ts3Functions.logMessage("Failed mailslot ReadFile", LogLevel_ERROR, "NiftyKb Plugin", 0); return PLUGIN_ERROR_READ_FAILED; } // Separate the argument from the command arg = strchr(messageStr, ' '); if (arg != NULL) { // Split the string by inserting a NULL-terminator *arg = (char)NULL; arg++; } // Parse debug string ParseCommand(messageStr, arg); // Free the debug string free(messageStr); } return PLUGIN_ERROR_NONE; }
// Função relativa à thread do servidor TCP. é o intermédio entre o client OPC e o client TCP, // trocando assim mensagens constantemente entre ambos os clientes. DWORD WINAPI TCPServer(LPVOID id) { WSADATA wsaData; int iResult; SOCKET ListenSocket = INVALID_SOCKET; SOCKET ClientSocket = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; int iSendResult; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; int seqdados = 0; char ack_string[13]; char ack_data[14]; char msgreq[TAMMSGREQ+1]; char msgsp[TAMMSGSP+1]; Monitor<vector<int>> mSocket(VERB_ON); char dados2[55]; char dados1[100]; LPTSTR MailSlotDados = TEXT("\\\\.\\mailslot\\mailslotDados"); //Inicializa mailslot Dados (caminho da troca de dados de processo) LPTSTR MailSlotSP = TEXT("\\\\.\\mailslot\\mailslotSP"); //Inicializa mailslot SP (caminho da troca de setpoints) HANDLE hSlotDados = CreateMailslot(MailSlotDados, //Criação do mailslot de dados //Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365785%28v=vs.85%29.aspx 0, // no maximum message size MAILSLOT_WAIT_FOREVER, // no time-out for operations (LPSECURITY_ATTRIBUTES) NULL); // default security if (hSlotDados == INVALID_HANDLE_VALUE) { printf("CreateMailslot failed with %d\n", GetLastError()); return FALSE; } else printf("MailslotDados created successfully.\n"); HANDLE hFileSP = CreateFile(MailSlotSP, // Abertura de arquivo para leitura do mailslot de setpoints // Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365802%28v=vs.85%29.aspx GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL); if (hFileSP == INVALID_HANDLE_VALUE) printf("CreateFile failed with %d.\n", GetLastError()); else printf("MailSlotSP File criado.\n"); // Criação de um evento para sincronizar a leitura do mailslot de setpoints. // Este evento será setado após os setpoints serem escritos no arquivo, // desta forma, o client OPC apenas vai ler deste quando tal ocorrer. HANDLE hMSWrite = CreateEvent(NULL, FALSE, FALSE, TEXT("hMSWrite")); if (hMSWrite == INVALID_HANDLE_VALUE) printf("Handle hMSWrite failed with %d.\n", GetLastError()); else printf("hMSWrite, handle criado.\n"); // Daqui em diante, grande parte do código de inicialização de um servidor TCP foi retirado do MSDN // https://msdn.microsoft.com/pt-br/library/windows/desktop/ms737593%28v=vs.85%29.aspx // A partir do código acima, alterações foram feitas para que a comunicação também com o Cliente OPC ocorresse // e também para que reconexões possam ser feitas. O servidor continua a tratar apenas um cliente simultâneo, // visto que não era previsto múltiplos acessos pela especificação do trabalho prático (apenas um computador do processo) // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } printf("TCP Server inicializado.\n");//Linha adicionada ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if ( iResult != 0 ) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } printf("Endereco resolvido.\n");//Linha adicionada // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } printf("Socket TCP criado.\n");//Linha adicionada // Setup the TCP listening socket iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } printf("Socket TCP de escuta inicializado.\n");//Linha adicionada freeaddrinfo(result); while(1){ // Este While permite que após uma conexão ser finalizada, o servidor volte a // escutar por uma nova conexão. iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } printf("Socket TCP ouvindo.\n");//Linha adicionada // Accept a client socket ClientSocket = accept(ListenSocket, NULL, NULL); printf("Cliente conectado.\n"); //Linha adicionada if (ClientSocket == INVALID_SOCKET) { printf("accept failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Daqui para baixo grande parte do código foi alterado, // visando a comunicação bilateral com TCP Cliente e OPC Cliente do { // Receber pedido de dados iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); // Testa se uma mensagem chegou if (iResult > 0) { // Analise da mensagem. Requisicao de pacotes? if (iResult == TAMMSGREQ){ strncpy_s(msgreq, sizeof(msgreq), recvbuf, iResult); // Confirmacao de requisicao. Testa tag inicial if (strncmp(msgreq, "100000", 6) == 0){ printf("Requisicao de pacotes recebida!\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult); // Caso a mensagem recebida for uma requisicao de pacotes, aguarda que estes sejam enviados pelo cliente OPC // e os repassa ao cliente TCP ReadSlot(hSlotDados,recvbuf); // Monta a mensagem com os dados mais uma tag identificadora e uma contagem sequencial sprintf_s(dados1,"200000|%.6d|%s",seqdados,recvbuf); // Envia dados em resposta ao pedido memcpy_s(&dados2, 55, dados1, 55); iSendResult = send( ClientSocket, dados2, 55, 0 ); // Incrementa sequenciador seqdados++; // Teste do envio if (iSendResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); iResult = 0; } } // Tag inicial desconhecida else { printf("Mensagem nao identificada recebida.\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult); iResult = 0; } } //IF result = request // Analise da mensagem. Envio de set points? else if (iResult == TAMMSGSP){ strncpy_s(msgsp, sizeof(msgsp), recvbuf, iResult); // Confirmacao da chegada de set points. Testa tag inicial if (strncmp(msgsp, "300000", 6) == 0){ printf("Set-points recebidos!\nMsg recebida: %s\nBytes recebidos: %d\n", msgsp, iResult); // Caso a mensagem recebida for um envio de setpoints, repassa-os ao cliente OPC e sinaliza o envio WriteSlot(hFileSP,msgsp); SetEvent(hMSWrite); // Monta uma nova mensagem e envia um ACK de confirmação ao cliente TCP sprintf_s(ack_data,"%s|%c%c%c%c%c%c",ACKDATA,recvbuf[7],recvbuf[8],recvbuf[9],recvbuf[10],recvbuf[11],recvbuf[12]); memcpy_s(&ack_string, 13, ack_data, 13); iSendResult = send(ClientSocket,ack_string,TAMMSGACK,0); // Teste do envio if (iSendResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); iResult = 0; } } // Tag inicial desconhecida else { printf("Mensagem nao identificada recebida.\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult); iResult = 0; } } //IF result = sp } //IF result > 0 else if (iResult == 0) printf("Connection closing...\n"); else { printf("recv failed with error: %d\n", WSAGetLastError()); iResult = 0; } } while (iResult > 0); cout << "Aguardando reconexao..." << endl; } // No longer need server socket closesocket(ListenSocket); //Inicialização sockets // shutdown the connection since we're done iResult = shutdown(ClientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } // cleanup CloseHandle(hMSWrite); CloseHandle(hSlotDados); CloseHandle(hFileSP); closesocket(ClientSocket); WSACleanup(); return(0); }
void w32gMailslotThread(void) { int i; char buffer[1024]; int size; MailslotArgcArgv.argc = 0; MailslotArgcArgv.argv = NULL; for(i=0;i<10;i++){ hMailslot = CreateMailslot(TIMIDITY_MAILSLOT,0,MAILSLOT_WAIT_FOREVER,(LPSECURITY_ATTRIBUTES)NULL); if (hMailslot != INVALID_HANDLE_VALUE) { break; } hMailslot = NULL; Sleep(300); } if(hMailslot==NULL){ return; } for(;;){ Sleep(1000); if(MailslotThreadTeminateFlag==TRUE){ if(hMailslot!=NULL) CloseHandle(hMailslot); break; } for(;;){ Sleep(200); if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ Sleep(1000); continue; } if(strcasecmp(buffer,MC_HEADER)!=0){ continue; } if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ Sleep(1000); continue; } if(strcasecmp(buffer,MC_TERMINATE)==0){ CloseHandle(hMailslot); w32g_send_rc(RC_STOP, 0); w32g_send_rc(RC_QUIT, 0); // PostThreadMessage(dwWindowThreadID,WM_CLOSE,0,0); // PostThreadMessage(dwWindowThreadID,WM_QUIT,0,0); Sleep(500); return; } if(strcasecmp(buffer,MC_FILES)==0){ char **files; int nfiles; int flag = TRUE; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } nfiles = atoi(buffer); // MailslotArgcArgv が初期化されていなかったら処理途中として無視 if(MailslotArgcArgv.argc!=0 || MailslotArgcArgv.argv!=NULL){ ReadFromMailslotIgnore(hMailslot,nfiles); continue; } files = (char **)malloc(sizeof(char *)*nfiles); if(files==NULL){ ReadFromMailslotIgnore(hMailslot,nfiles); continue; } for(i=0;i<nfiles;i++){ if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ flag = FALSE; break; } files[i] = (char *)malloc(sizeof(char)*(size+1)); if(files[i]==NULL){ int j; ReadFromMailslotIgnore(hMailslot,nfiles-i-1); for(j=0;j<i;j++){ free(files[j]); } flag = FALSE; break; } strncpy(files[i],buffer,size); files[i][size] = 0; } if(flag==FALSE){ free(files); continue; } MailslotArgcArgv.argc = nfiles; MailslotArgcArgv.argv = files; // files は別のところで解放してくれる w32g_send_rc(RC_EXT_LOAD_FILES_AND_PLAY,(ptr_size_t)&MailslotArgcArgv); // w32g_send_rc(RC_EXT_LOAD_FILE,(ptr_size_t))files[0]); continue; } if(strcasecmp(buffer,MC_PLAYLIST_CLEAR)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_EXT_CLEAR_PLAYLIST,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_PLAY)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_LOAD_FILE,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_PLAY_NEXT)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_NEXT,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_PLAY_PREV)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_REALLY_PREVIOUS,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_STOP)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_STOP,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_PAUSE)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); w32g_send_rc(RC_PAUSE,0); ReadFromMailslotIgnore(hMailslot,param_num); continue; } if(strcasecmp(buffer,MC_SEND_TIMIDITY_INFO)==0){ int param_num; if(ReadFromMailslot(hMailslot,buffer,&size)==FALSE){ continue; } param_num = atoi(buffer); ReadFromMailslotIgnore(hMailslot,param_num); // 何もしない continue; } } } }
__declspec(dllexport) void __cdecl VDDDispatch(void) { char str[512]; DWORD count; DWORD msgs; int retval; int node_num; BYTE* p; vdd_status_t* status; static DWORD writes; static DWORD bytes_written; static DWORD reads; static DWORD bytes_read; static DWORD inbuf_poll; static DWORD online_poll; static DWORD status_poll; static DWORD vdd_yields; static DWORD vdd_calls; VDD_IO_HANDLERS IOHandlers = { NULL }; static VDD_IO_PORTRANGE PortRange; retval=0; node_num=getBH(); lprintf(LOG_DEBUG,"VDD_OP: (handle=%d) %d (arg=%X)", getAX(),getBL(),getCX()); vdd_calls++; switch(getBL()) { case VDD_OPEN: sscanf("$Revision: 1.40 $", "%*s %s", revision); lprintf(LOG_INFO,"Synchronet Virtual Device Driver, rev %s %s %s" ,revision, __DATE__, __TIME__); #if 0 sprintf(str,"sbbsexec%d.log",node_num); fp=fopen(str,"wb"); #endif sprintf(str,"\\\\.\\mailslot\\sbbsexec\\wr%d",node_num); rdslot=CreateMailslot(str ,0 //LINEAR_RX_BUFLEN /* Max message size (0=any) */ ,MAILSLOT_WAIT_FOREVER /* Read timeout */ ,NULL); if(rdslot==INVALID_HANDLE_VALUE) { lprintf(LOG_ERR,"!VDD_OPEN: Error %d opening %s" ,GetLastError(),str); retval=1; break; } sprintf(str,"\\\\.\\mailslot\\sbbsexec\\rd%d",node_num); wrslot=CreateFile(str ,GENERIC_WRITE ,FILE_SHARE_READ ,NULL ,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL ,(HANDLE) NULL); if(wrslot==INVALID_HANDLE_VALUE) { lprintf(LOG_ERR,"!VDD_OPEN: Error %d opening %s" ,GetLastError(),str); retval=2; break; } if(RingBufInit(&rdbuf, RINGBUF_SIZE_IN)!=0) { retval=3; break; } sprintf(str,"sbbsexec_hungup%d",node_num); hungup_event=OpenEvent( EVENT_ALL_ACCESS, /* access flag */ FALSE, /* inherit flag */ str); /* pointer to event-object name */ if(hungup_event==NULL) { lprintf(LOG_ERR,"!VDD_OPEN: Error %d opening %s" ,GetLastError(),str); retval=4; break; } sprintf(str,"sbbsexec_hangup%d",node_num); hangup_event=OpenEvent( EVENT_ALL_ACCESS, /* access flag */ FALSE, /* inherit flag */ str); /* pointer to event-object name */ if(hangup_event==NULL) { lprintf(LOG_WARNING,"!VDD_OPEN: Error %d opening %s" ,GetLastError(),str); } status_poll=0; inbuf_poll=0; online_poll=0; yields=0; lprintf(LOG_INFO,"Yield interval: %f milliseconds", yield_interval); if(virtualize_uart) { lprintf(LOG_INFO,"Virtualizing UART (0x%x, IRQ %u)" ,uart_io_base, uart_irq); IOHandlers.inb_handler = uart_rdport; IOHandlers.outb_handler = uart_wrport; PortRange.First=uart_io_base; PortRange.Last=uart_io_base + UART_IO_RANGE; VDDInstallIOHook((HANDLE)getAX(), 1, &PortRange, &IOHandlers); interrupt_event=CreateEvent(NULL,FALSE,FALSE,NULL); InitializeCriticalSection(&interrupt_mutex); _beginthread(interrupt_thread, 0, NULL); } lprintf(LOG_DEBUG,"VDD_OPEN: Opened successfully (wrslot=%p)", wrslot); _beginthread(input_thread, 0, NULL); retval=0; break; case VDD_CLOSE: lprintf(LOG_INFO,"VDD_CLOSE: rdbuf=%u " "status_poll=%u inbuf_poll=%u online_poll=%u yields=%u vdd_yields=%u vdd_calls=%u" ,RingBufFull(&rdbuf),status_poll,inbuf_poll,online_poll ,yields,vdd_yields,vdd_calls); lprintf(LOG_INFO," read=%u bytes (in %u calls)",bytes_read,reads); lprintf(LOG_INFO," wrote=%u bytes (in %u calls)",bytes_written,writes); if(virtualize_uart) { lprintf(LOG_INFO,"Uninstalling Virtualizaed UART IO Hook"); VDDDeInstallIOHook((HANDLE)getAX(), 1, &PortRange); } CloseHandle(rdslot); CloseHandle(wrslot); if(hungup_event!=NULL) CloseHandle(hungup_event); if(hangup_event!=NULL) CloseHandle(hangup_event); #if 0 /* This isn't strictly necessary... and possibly the cause of a NULL dereference in the input_thread */ RingBufDispose(&rdbuf); #endif status_poll=0; retval=0; break; case VDD_READ: count = getCX(); if(count != 1) lprintf(LOG_DEBUG,"VDD_READ of %d",count); p = (BYTE*) GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); retval=vdd_read(p, count); reads++; bytes_read+=retval; reset_yield(); break; case VDD_PEEK: count = getCX(); if(count != 1) lprintf(LOG_DEBUG,"VDD_PEEK of %d",count); p = (BYTE*) GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); retval=RingBufPeek(&rdbuf,p,count); reset_yield(); break; case VDD_WRITE: count = getCX(); if(count != 1) lprintf(LOG_DEBUG,"VDD_WRITE of %d",count); p = (BYTE*) GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); if(!WriteFile(wrslot,p,count,&retval,NULL)) { lprintf(LOG_ERR,"!VDD_WRITE: WriteFile Error %d (size=%d)" ,GetLastError(),retval); retval=0; } else { writes++; bytes_written+=retval; reset_yield(); } break; case VDD_STATUS: status_poll++; count = getCX(); if(count != sizeof(vdd_status_t)) { lprintf(LOG_DEBUG,"!VDD_STATUS: wrong size (%d!=%d)",count,sizeof(vdd_status_t)); retval=sizeof(vdd_status_t); break; } status = (vdd_status_t*) GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); status->inbuf_size=RINGBUF_SIZE_IN; status->inbuf_full=RingBufFull(&rdbuf); msgs=0; /* OUTBUF FULL/SIZE */ if(!GetMailslotInfo( wrslot, /* mailslot handle */ &status->outbuf_size, /* address of maximum message size */ &status->outbuf_full, /* address of size of next message */ &msgs, /* address of number of messages */ NULL /* address of read time-out */ )) { lprintf(LOG_ERR,"!VDD_STATUS: GetMailSlotInfo(%p) failed, error %u (msgs=%u, inbuf_full=%u, inbuf_size=%u)" ,wrslot ,GetLastError(), msgs, status->inbuf_full, status->inbuf_size); status->outbuf_full=0; status->outbuf_size=DEFAULT_MAX_MSG_SIZE; } else lprintf(LOG_DEBUG,"VDD_STATUS: MailSlot maxmsgsize=%u, nextmsgsize=%u, msgs=%u" ,status->outbuf_size ,status->outbuf_full ,msgs); if(status->outbuf_full==MAILSLOT_NO_MESSAGE) status->outbuf_full=0; status->outbuf_full*=msgs; /* ONLINE */ if(WaitForSingleObject(hungup_event,0)==WAIT_OBJECT_0) status->online=0; else status->online=1; retval=0; /* success */ break; case VDD_INBUF_PURGE: RingBufReInit(&rdbuf); retval=0; break; case VDD_OUTBUF_PURGE: lprintf(LOG_WARNING,"!VDD_OUTBUF_PURGE: NOT IMPLEMENTED"); retval=0; break; case VDD_INBUF_FULL: retval=RingBufFull(&rdbuf); inbuf_poll++; break; case VDD_INBUF_SIZE: retval=RINGBUF_SIZE_IN; break; case VDD_OUTBUF_FULL: if(!GetMailslotInfo( wrslot, /* mailslot handle */ NULL, /* address of maximum message size */ &retval, /* address of size of next message */ &msgs, /* address of number of messages */ NULL /* address of read time-out */ )) retval=0; if(retval==MAILSLOT_NO_MESSAGE) retval=0; retval*=msgs; break; case VDD_OUTBUF_SIZE: if(!GetMailslotInfo( wrslot, /* mailslot handle */ &retval, /* address of maximum message size */ NULL, /* address of size of next message */ NULL, /* address of number of messages */ NULL /* address of read time-out */ )) retval=DEFAULT_MAX_MSG_SIZE; break; case VDD_ONLINE: if(WaitForSingleObject(hungup_event,0)==WAIT_OBJECT_0) retval=0; else retval=1; online_poll++; break; case VDD_YIELD: /* forced yield */ vdd_yields++; yield(); break; case VDD_MAYBE_YIELD: /* yield if YieldInterval is enabled and expired */ maybe_yield(); break; case VDD_LOAD_INI_FILE: /* Load and parse settings file */ { FILE* fp; char cwd[MAX_PATH+1]; /* Load exec/sbbsexec.ini first (setting default values) */ count = getCX(); p = (BYTE*)GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); iniFileName(ini_fname, sizeof(ini_fname), p, INI_FILENAME); if((fp=fopen(ini_fname,"r"))!=NULL) { ini=iniReadFile(fp); fclose(fp); parse_ini(ROOT_SECTION); } /* Load cwd/sbbsexec.ini second (over-riding default values) */ GetCurrentDirectory(sizeof(cwd),cwd); iniFileName(ini_fname, sizeof(ini_fname), cwd, INI_FILENAME); if((fp=fopen(ini_fname,"r"))!=NULL) { ini=iniReadFile(fp); fclose(fp); parse_ini(ROOT_SECTION); } } break; case VDD_LOAD_INI_SECTION: /* Parse (program-specific) sub-section of settings file */ count = getCX(); p = (BYTE*)GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); parse_ini(p); break; case VDD_DEBUG_OUTPUT: /* Send string to debug output */ count = getCX(); p = (BYTE*)GetVDMPointer((ULONG)((getES() << 16)|getDI()) ,count,FALSE); lputs(LOG_INFO, p); break; case VDD_HANGUP: hangup(); break; default: lprintf(LOG_ERR,"!UNKNOWN VDD_OP: %d",getBL()); break; } setAX((WORD)retval); }
int rlMailbox::read(void *buf, int maxlen, int wait) { char *cbuf; status = OK; cbuf = (char *) buf; #ifdef RLUNIX int len; unsigned char *message = new unsigned char [sizeof(long) + maxlen]; if(wait == WAIT ) len = msgrcv(chanid,(struct msgbuf *) message, maxlen,0,0); else len = msgrcv(chanid,(struct msgbuf *) message, maxlen,0,IPC_NOWAIT); if(len < maxlen && len >= 0) { memcpy(buf,&message[sizeof(long)],len); cbuf[len] = '\0'; } else { cbuf[0] = '\0'; } delete [] message; return len; #endif #ifdef __VMS int ret,len; IOSB iosb; if(wait == NOWAIT) { ret = sys$qiow(0, (short) chanid, IO$_READVBLK | IO$M_NOW, // I/O CODE &iosb, 0,0, buf, maxlen,0,0,0,0); } else { ret = sys$qiow(0, (short) chanid, IO$_READVBLK, // I/O CODE &iosb, 0,0, buf, maxlen,0,0,0,0); } len = (int) iosb.msg_len; if(len < maxlen && len >= 0) cbuf[len] = '\0'; if (ret == SS$_NORMAL && iosb.iostat == SS$_NORMAL) return len; else if(iosb.iostat == SS$_NORMAL) { status = -1; return MAILBOX_ERROR; } else if(ret == SS$_NORMAL) { if(wait == NOWAIT && iosb.iostat == SS$_ENDOFFILE) { status = -2; return MAILBOX_ERROR; } else { status = -3; return MAILBOX_ERROR; } } status = -4; return MAILBOX_ERROR; #endif #ifdef RLWIN32 HANDLE h; char mbxname[1024]; unsigned long lenRead; BOOL bret,bret2; if(chanid == -1) { strcpy(mbxname,"\\\\.\\mailslot\\"); strcat(mbxname,name); h = CreateMailslot( mbxname, // pointer to string for mailslot name MAX_MAILBOX, // maximum message size MAILSLOT_WAIT_FOREVER, // milliseconds before read time-out NULL); // pointer to security structure if(h == INVALID_HANDLE_VALUE) { status = GetLastError(); return MAILBOX_ERROR; } chanid = (int) h; bret2 = SetMailslotInfo((HANDLE) chanid, MAILSLOT_WAIT_FOREVER); if(bret2 == 0) { status = GetLastError(); return MAILBOX_ERROR; } } if(wait == NOWAIT) // begin wait { lenRead = 0; bret2 = SetMailslotInfo((HANDLE) chanid, 0); if(bret2 == 0) { status = GetLastError(); return MAILBOX_ERROR; } bret = ReadFile( (HANDLE) chanid, // handle of file to read buf, // pointer to buffer maxlen, // number of bytes to read &lenRead, // pointer to number of bytes read NULL // pointer to structure for data ); bret2 = SetMailslotInfo((HANDLE) chanid, MAILSLOT_WAIT_FOREVER); if(bret2 == 0) { status = GetLastError(); return MAILBOX_ERROR; } if(bret == 0) { status = GetLastError(); return MAILBOX_ERROR; } if((int) lenRead < maxlen && (int) lenRead >= 0) cbuf[lenRead] = '\0'; return lenRead; } // end wait lenRead = 0; bret = ReadFile( (HANDLE) chanid, // handle of file to read buf, // pointer to buffer maxlen, // number of bytes to read &lenRead, // pointer to number of bytes read NULL // pointer to structure for data ); if(bret == 0) { status = GetLastError(); return MAILBOX_ERROR; } if((int) lenRead < maxlen && (int) lenRead >= 0) cbuf[lenRead] = '\0'; return lenRead; #endif }
static int mailslot_test(void) { HANDLE hSlot, hSlot2, hWriter, hWriter2; unsigned char buffer[16]; DWORD count, dwMax, dwNext, dwMsgCount, dwTimeout; /* sanity check on GetMailslotInfo */ dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( !GetMailslotInfo( INVALID_HANDLE_VALUE, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo succeeded\n"); /* open a mailslot that doesn't exist */ hWriter = CreateFile(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter == INVALID_HANDLE_VALUE, "nonexistent mailslot\n"); /* open a mailslot without the right name */ hSlot = CreateMailslot( "blah", 0, 0, NULL ); ok( hSlot == INVALID_HANDLE_VALUE, "Created mailslot with invalid name\n"); ok( GetLastError() == ERROR_INVALID_NAME, "error should be ERROR_INVALID_NAME\n"); /* open a mailslot with a null name */ hSlot = CreateMailslot( NULL, 0, 0, NULL ); ok( hSlot == INVALID_HANDLE_VALUE, "Created mailslot with invalid name\n"); ok( GetLastError() == ERROR_PATH_NOT_FOUND, "error should be ERROR_PATH_NOT_FOUND\n"); /* valid open, but with wacky parameters ... then check them */ hSlot = CreateMailslot( szmspath, -1, -1, NULL ); ok( hSlot != INVALID_HANDLE_VALUE , "mailslot with valid name failed\n"); dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( GetMailslotInfo( hSlot, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo failed\n"); ok( dwMax == ~0U, "dwMax incorrect\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); ok( dwTimeout == ~0U, "dwTimeout incorrect\n"); ok( GetMailslotInfo( hSlot, NULL, NULL, NULL, NULL ), "getmailslotinfo failed\n"); ok( CloseHandle(hSlot), "failed to close mailslot\n"); /* now open it for real */ hSlot = CreateMailslot( szmspath, 0, 0, NULL ); ok( hSlot != INVALID_HANDLE_VALUE , "valid mailslot failed\n"); /* try and read/write to it */ count = 0; memset(buffer, 0, sizeof buffer); ok( !ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); ok( !WriteFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot write\n"); /* now try and openthe client, but with the wrong sharing mode */ hWriter = CreateFile(szmspath, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter == INVALID_HANDLE_VALUE, "bad sharing mode\n"); ok( GetLastError() == ERROR_SHARING_VIOLATION, "error should be ERROR_SHARING_VIOLATION\n"); /* now open the client with the correct sharing mode */ hWriter = CreateFile(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter != INVALID_HANDLE_VALUE, "existing mailslot\n"); /* * opening a client should make no difference to * whether we can read or write the mailslot */ ok( !ReadFile( hSlot, buffer, sizeof buffer/2, &count, NULL), "slot read\n"); ok( !WriteFile( hSlot, buffer, sizeof buffer/2, &count, NULL), "slot write\n"); /* * we can't read from this client, * but we should be able to write to it */ ok( !ReadFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can read client\n"); ok( WriteFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can't write client\n"); ok( !ReadFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can read client\n"); /* * seeing as there's something in the slot, * we should be able to read it once */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); ok( count == (sizeof buffer/2), "short read\n" ); /* but not again */ ok( !ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); /* now try open another writer... should fail */ hWriter2 = CreateFile(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 == INVALID_HANDLE_VALUE, "two writers\n"); /* now try open another as a reader ... also fails */ hWriter2 = CreateFile(szmspath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 == INVALID_HANDLE_VALUE, "writer + reader\n"); /* now try open another as a writer ... still fails */ hWriter2 = CreateFile(szmspath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 == INVALID_HANDLE_VALUE, "writer\n"); /* now open another one */ hSlot2 = CreateMailslot( szmspath, 0, 0, NULL ); ok( hSlot2 == INVALID_HANDLE_VALUE , "opened two mailslots\n"); /* close the client again */ ok( CloseHandle( hWriter ), "closing the client\n"); /* * now try reopen it with slightly different permissions ... * shared writing */ hWriter = CreateFile(szmspath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter != INVALID_HANDLE_VALUE, "sharing writer\n"); /* * now try open another as a writer ... * but don't share with the first ... fail */ hWriter2 = CreateFile(szmspath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 == INVALID_HANDLE_VALUE, "greedy writer succeeded\n"); /* now try open another as a writer ... and share with the first */ hWriter2 = CreateFile(szmspath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 != INVALID_HANDLE_VALUE, "2nd sharing writer\n"); /* check the mailslot info */ dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( GetMailslotInfo( hSlot, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo failed\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMax == 0, "dwMax incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); ok( dwTimeout == 0, "dwTimeout incorrect\n"); /* check there's still no data */ ok( !ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); /* write two messages */ buffer[0] = 'a'; ok( WriteFile( hWriter, buffer, 1, &count, NULL), "1st write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); ok( dwMsgCount == 1, "dwMsgCount incorrect\n"); buffer[0] = 'b'; buffer[1] = 'c'; ok( WriteFile( hWriter2, buffer, 2, &count, NULL), "2nd write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); todo_wine { ok( dwMsgCount == 2, "dwMsgCount incorrect\n"); } /* write a 3rd message with zero size */ ok( WriteFile( hWriter2, buffer, 0, &count, NULL), "3rd write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); todo_wine { ok( dwMsgCount == 3, "dwMsgCount incorrect\n"); } buffer[0]=buffer[1]=0; /* * then check that they come out with the correct order and size, * then the slot is empty */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "1st slot read failed\n"); ok( count == 1, "failed to get 1st message\n"); ok( buffer[0] == 'a', "1st message wrong\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 2, "dwNext incorrect\n"); todo_wine { ok( dwMsgCount == 2, "dwMsgCount incorrect\n"); } /* read the second message */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "2nd slot read failed\n"); ok( count == 2, "failed to get 2nd message\n"); ok( ( buffer[0] == 'b' ) && ( buffer[1] == 'c' ), "2nd message wrong\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); todo_wine { ok( dwNext == 0, "dwNext incorrect\n"); ok( dwMsgCount == 1, "dwMsgCount incorrect\n"); } /* read the 3rd (zero length) message */ todo_wine { ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "3rd slot read failed\n"); } ok( count == 0, "failed to get 3rd message\n"); /* * now there should be no more messages * check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); /* check that reads fail */ ok( !ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "3rd slot read succeeded\n"); /* finally close the mailslot and its client */ ok( CloseHandle( hWriter2 ), "closing 2nd client\n"); ok( CloseHandle( hWriter ), "closing the client\n"); ok( CloseHandle( hSlot ), "closing the mailslot\n"); return 0; }
STATIC NET_API_STATUS AlInitializeAlerter( VOID ) /*++ Routine Description: This routine initializes the Alerter service. Arguments: AlInitState - Returns a flag to indicate how far we got with initializing the Alerter service before an error occured. Return Value: NET_API_STATUS - NERR_Success or reason for failure. --*/ { NET_API_STATUS status; NTSTATUS ntstatus; PSECURITY_DESCRIPTOR Sd; SECURITY_ATTRIBUTES Sa; ACE_DATA AceData[1] = { {ACCESS_ALLOWED_ACE_TYPE, 0, 0, GENERIC_READ | GENERIC_WRITE, &AlLmsvcsGlobalData->WorldSid} }; AlGlobalData.MailslotHandle = (HANDLE) MAXULONG; // // Initialize Alerter to receive service requests by registering the // control handler. // if ((AlGlobalData.StatusHandle = RegisterServiceCtrlHandler( SERVICE_ALERTER, AlerterControlHandler )) == (SERVICE_STATUS_HANDLE) NULL) { status = GetLastError(); AlHandleError(AlErrorRegisterControlHandler, status, NULL); return status; } // // Initialize all the status fields so that subsequent calls to // SetServiceStatus need to only update fields that changed. // AlGlobalData.Status.dwServiceType = SERVICE_WIN32; AlGlobalData.Status.dwCurrentState = SERVICE_START_PENDING; AlGlobalData.Status.dwControlsAccepted = 0; AlGlobalData.Status.dwCheckPoint = 1; AlGlobalData.Status.dwWaitHint = 10000; // 10 secs SET_SERVICE_EXITCODE( NO_ERROR, AlGlobalData.Status.dwWin32ExitCode, AlGlobalData.Status.dwServiceSpecificExitCode ); // // Tell the Service Controller that we are start-pending // if ((status = AlUpdateStatus()) != NERR_Success) { AlHandleError(AlErrorNotifyServiceController, status, NULL); return status; } // // Get the configured alert names // if ((status = AlGetAlerterConfiguration()) != NERR_Success) { AlHandleError(AlErrorGetComputerName, status, NULL); return status; } // // Create the security descriptor for the security attributes structure // ntstatus = NetpCreateSecurityDescriptor( AceData, 1, AlLmsvcsGlobalData->LocalSystemSid, AlLmsvcsGlobalData->LocalSystemSid, &Sd ); if (! NT_SUCCESS(ntstatus)) { status = NetpNtStatusToApiStatus(ntstatus); AlHandleError(AlErrorCreateMailslot, status, NULL); return status; } Sa.nLength = sizeof(SECURITY_ATTRIBUTES); Sa.lpSecurityDescriptor = Sd; Sa.bInheritHandle = FALSE; // // Create mailslot to listen on alert notifications from the Server // service and the Spooler. // AlGlobalData.MailslotHandle = CreateMailslot( ALERTER_MAILSLOT, MAX_MAILSLOT_MESSAGE_SIZE, MAILSLOT_WAIT_FOREVER, &Sa ); NetpMemoryFree(Sd); if (AlGlobalData.MailslotHandle == (HANDLE) MAXULONG) { status = GetLastError(); AlHandleError(AlErrorCreateMailslot, status, NULL); return status; } else { IF_DEBUG(MAIN) { NetpKdPrint(("Mailslot %ws created, handle=x%08lx\n", ALERTER_MAILSLOT, AlGlobalData.MailslotHandle)); } } // // Tell the Service Controller that we are started. // AlGlobalData.Status.dwCurrentState = SERVICE_RUNNING; AlGlobalData.Status.dwControlsAccepted = SERVICE_ACCEPT_STOP; AlGlobalData.Status.dwCheckPoint = 0; AlGlobalData.Status.dwWaitHint = 0; if ((status = AlUpdateStatus()) != NERR_Success) { AlHandleError(AlErrorNotifyServiceController, status, NULL); return status; } IF_DEBUG(MAIN) { NetpKdPrint(("[Alerter] Successful Initialization\n")); } return NERR_Success; }
LRESULT CALLBACK WndProc(HWND h, UINT im, WPARAM wp, LPARAM lp) { switch (im) { case WM_CREATE: { HANDLE mailslot; DWORD recvSize; // 메일슬롯 만들기 mailslot = CreateFile(MSLOT, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (mailslot == INVALID_HANDLE_VALUE) { mailslot = CreateMailslot(MSLOT, 0, 0, NULL); isServer = true; } else { isServer = false; } // Random Seed srand((unsigned)time(NULL)); // 0.1초마다 갱신 SetTimer(h, 0, 100, NULL); // 화면 얻기 RECT rect; GetClientRect(h, &rect); width = rect.right - rect.left; height = rect.bottom - rect.top; // 세마포어 sep = CreateSemaphore(NULL, 1, 1, L""); // 공 45개 만들기 // 서버일 경우 if (isServer) { for (int i = 0; i < 45; i++) { balls[i].id = i + 1; balls[i].x = 50 + 100 * (i % 9); // row balls[i].y = 50 + 100 * (i / 9); // column balls[i].hdc = hdc; balls[i].sep = sep; balls[i].h = h; // 랜덤 이동 변수 -1 ~ 1 randomX[i] = 3 * ((rand() % 2) * 2 - 1); randomY[i] = 3 * ((rand() % 2) * 2 - 1); } } // 클라이언트 일 경우 else { for (int i = 0; i < 7; i++) { balls[i].id = (rand() % 45) + 1; for (int j = 0; j < i; j++) { if (balls[j].id == balls[i].id) { i--; break; } } balls[i].h = h; balls[i].hdc = hdc; balls[i].sep = sep; balls[i].x = 200 + 100 * i; balls[i].y = height / 2; // 랜덤 이동 변수 -1 ~ 1 randomX[i] = (rand() % 2); randomY[i] = (rand() % 2); } } break; } case WM_TIMER: { // 서버일 경우 if (isServer) { for (int i = 0; i < 45; i++) { balls[i].x += randomX[i]; balls[i].y += randomY[i]; if (balls[i].x < 0 || balls[i].x > width) { randomX[i] *= -1; } if (balls[i].y<0 || balls[i].y>height) { randomY[i] *= -1; } threadArray[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)&balls[i], 0, &threadID); } // THREAD JOIN if (threadArray != NULL) { WaitForMultipleObjects(45, threadArray, TRUE, INFINITE); } } // 클라이언트인 경우 else { for (int i = 0; i < 7; i++) { balls[i].x += randomX[i]; balls[i].y += randomY[i]; threadArray[i] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)&balls[i], 0, &threadID); Sleep(1000); } } break; } case WM_LBUTTONDOWN: if (isServer) { // 자식 프로세스 생성 wchar_t title[10] = L"Lotto.exe"; STARTUPINFO si = { 0, }; CreateProcess(NULL, title, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi); } else { // 종료 PostQuitMessage(0); } break; case WM_DESTROY: PostQuitMessage(0); break; } return(DefWindowProc(h, im, wp, lp)); }
int _CRTAPI1 main( int argc, char * argv[] ) { NET_API_STATUS ApiStatus = NO_ERROR; int ArgNumber; DWORD bytes_read; BOOL DoHexDump = FALSE; TCHAR MailslotName[FULL_SLOT_NAME_SIZE+1]; BOOL Master = FALSE; DWORD MaxMailslotSize; time_t Now; HANDLE test_mailslot_handle = (HANDLE)(-1); BOOL Verbose = FALSE; // // Process command-line arguments for real. // for (ArgNumber = 1; ArgNumber < argc; ArgNumber++) { if ((*argv[ArgNumber] == '-') || (*argv[ArgNumber] == '/')) { switch (tolower(*(argv[ArgNumber]+1))) // Process switches { case 'h' : DoHexDump = TRUE; break; case 'm' : Master = TRUE; break; case 'v' : Verbose = TRUE; break; default: Usage( argv[0] ); return (EXIT_FAILURE); } } else { Usage( argv[0] ); return (EXIT_FAILURE); } } (void) STRCPY( MailslotName, SLASH_SLASH ); (void) STRCAT( MailslotName, DOT ); if (!Master) { (void) STRCAT( MailslotName, (LPTSTR) CLIENT_SLOT_NAME ); MaxMailslotSize = MAX_2_MSLOT_SIZE; } else { (void) STRCAT( MailslotName, (LPTSTR) MASTER_SLOT_NAME ); MaxMailslotSize = MAX_MSG; } (VOID) printf( "Creating mailslot '" FORMAT_LPTSTR "' of size " FORMAT_DWORD "...\n", MailslotName, MaxMailslotSize ); test_mailslot_handle = CreateMailslot( MailslotName, MaxMailslotSize, (DWORD) MAILSLOT_WAIT_FOREVER, // readtimeout NULL ); // security attributes if ( test_mailslot_handle == (HANDLE)(-1) ) { ApiStatus = (NET_API_STATUS) GetLastError(); assert( ApiStatus != NO_ERROR ); (VOID) printf( "CreateMailslot error: " FORMAT_API_STATUS "\n", ApiStatus ); goto Cleanup; } Now = time( NULL ); (VOID) printf( ctime( &Now ) ); while (TRUE) { if (Verbose) { (VOID) printf( "Waiting for next mailslot message...\n\n" ); } if ( !ReadFile( test_mailslot_handle, msg_buf, sizeof( msg_buf ), &bytes_read, NULL )) { // No overlapped I/O ApiStatus = (NET_API_STATUS) GetLastError(); assert( ApiStatus != NO_ERROR ); (VOID) printf( "ReadFile error: " FORMAT_API_STATUS "\n", ApiStatus ); goto Cleanup; // don't forget to close... } (VOID) Beep(1000, 500); (VOID) Beep(1500, 700); Now = time( NULL ); (VOID) printf( ctime( &Now ) ); if (DoHexDump) { NetpDbgHexDump( (LPVOID) msg_buf, // start of dump bytes_read); // size in bytes } DisplayPackedReplMailslotMsg( msg_buf, // start of msg bytes_read, // msg size in bytes Verbose ); } // while loop Cleanup: if ( test_mailslot_handle != (HANDLE)(-1) ) { (VOID) CloseHandle( test_mailslot_handle ); } if (ApiStatus == NO_ERROR) { return (EXIT_SUCCESS); } else { return (EXIT_FAILURE); } } // main()