int main(int argc, char** argv){ int socket = CreateServerSocket(8089); if(socket == -1){ printf("Uh-oh!\n"); exit(0); } ServerMainLoop(socket, 20, HandleRequest); }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, PSTR lpCmdLine, int nShowCmd) { WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH ); wc.hCursor = LoadCursor( 0, IDC_ARROW ); wc.hIcon = LoadIcon( 0, IDI_APPLICATION); wc.hInstance = hInstance; wc.lpfnWndProc = WndProc; wc.lpszClassName = "First"; wc.lpszMenuName = 0; wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; RegisterClass( &wc); HWND hwnd = CreateWindowEx( 0, "first", "Hello", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0); //------------------------------------------------------------------------- // Socket 관련 작업 !! //------------------------------------------------------------------------- SOCKET ListenSocket = CreateServerSocket(); WSAAsyncSelect( ListenSocket, // 네트워크 이벤트 발생하는 소켓 hwnd, // 네트워크 이벤트를 처리해줄 윈도우 UM_SOCKET, // 전달받을 메시지 FD_ACCEPT|FD_CLOSE ); // 처리할 이벤트 ShowWindow( hwnd, SW_SHOW ); UpdateWindow( hwnd ); MSG msg; while( GetMessage( &msg, 0, 0, 0) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } return 0; }
int _tmain(int argc, _TCHAR* argv[]) { // Khai bao bien WSADATA wsaData = {0}; int iRet = 0, iRetReturn = 0; SOCKET sockServer= INVALID_SOCKET; CHAR szIpAddress[20] = {0}; int iPort = 1080; addrinfo *result = NULL; SOCKADDR_IN serverAddr = {0}; int* pintClientSocket; SOCKADDR_IN clientAddr = {0}; int iAddr_size = sizeof(SOCKADDR); g_iNumberConnected = 0; if (!IsReadInfoServer()) { return 0; } printf("Bai Tap Lon Mon: Cac he thong phan tan."); printf("\nServer version 1.0"); printf("\n------------------------------------------"); iRet = CreateServerSocket(&wsaData, &sockServer); if (iRet == 1) { printf("\nKhoi tao socket khong thanh cong!"); iRetReturn = 1; goto RETURN; } // bind and listen serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(iPort); serverAddr.sin_addr.s_addr = INADDR_ANY ; if (bind(sockServer, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { printf("\nCo loi!"); iRetReturn = 1; goto RETURN; } if (listen(sockServer, g_iNumberConnected)) { printf("\nCo loi khi lang nghe ket noi!"); iRetReturn = 1; goto RETURN; } while(true) { printf("\nLang nghe ket noi:"); pintClientSocket = (int*)malloc(sizeof(int)); if((*pintClientSocket = accept( sockServer, (SOCKADDR*)&clientAddr, &iAddr_size))== INVALID_SOCKET ) { printf("\nLoi nhan ket noi!"); continue; } printf("\nNhan ket noi tu: %s",inet_ntoa(clientAddr.sin_addr)); CreateThread(NULL, NULL, &ConnectFromClient, (void*)pintClientSocket, NULL, NULL); } RETURN: return 0; }
static void * dispatcher_thread_handler( void * args) { int index = *((int *) args); free(args); int listenfd; struct sockaddr_in client_addr, server_addr; socklen_t addrLen; char query_buffer[NS_MAXMSG]; int queryLen; int port_num = PORT_DISPATCHER + index; listenfd = CreateServerSocket(AF_INET, SOCK_DGRAM, "127.0.0.1", PORT_DISPATCHER + index, (struct sockaddr *)&server_addr); if( listenfd <0) { my_log("Error: Cannot create server socket for dispatcher %d, port :%d \n", index, port_num); disp_addr[index].sockfd= -1; disp_addr[index].port= -1; pthread_exit(NULL); } disp_addr[index].port= port_num; //Tell the recv_send thread where I am ready disp_addr[index].ready= TRUE; debug("Dispatcher[%d] is ready\n", index); fd_set read_fds; int max = listenfd +1; int num, rcode; for (;;) { if (parentRequestStop) { //debug("dispacher[%d] will quit now on request.\n", index); break; } //debug("Dispatcher[%d] is working...\n", index); while(parentRequestPause){}; FD_ZERO(&read_fds); FD_SET(listenfd, &read_fds); struct timeval timeout={TIMEOUT,0}; int count = select(max, &read_fds, NULL, NULL, &timeout); if (count < 0) //Maybe Interrupted, such as ^C pressed { //break; continue; } if(count == 0) //No event in timeout { continue; } if (FD_ISSET(listenfd, &read_fds) ) { memset(query_buffer, 0, sizeof(query_buffer)); addrLen=sizeof(client_addr); //queryLen = recvfrom(listenfd, (char *) &num , NS_MAXMSG, 0, queryLen = recvfrom(listenfd, (char *) &num , sizeof(num), 0, (struct sockaddr * )&client_addr, &addrLen); if( queryLen < 2 || num <0 || num >= MAX_QUERY_NUM) { //my_log("Error: read index of query error, len=%d, num=%d\n", // queryLen, num); continue; } Query *pQuery = queries.queries[num]; //querylist_lookup_byIndex(&queries,num); if (pQuery == NULL) { //my_log("Error: Cannot find query[%d]\n", num); continue; } rcode = query_parse(pQuery); if ( rcode == -1) { //my_log("Error: Can't parse query in dispatch\n"); //it should be freed here querylist_free_item(&queries, num); continue; } long cAddr_h; struct sockaddr_in *pca; pca = &pQuery->client_addr; cAddr_h = ntohl(pca->sin_addr.s_addr); Action *pAct = policy_lookup(&policy, cAddr_h, pQuery->qname); //resolver_display( pAct->resolver); //char strAddr[MAX_WORD]; if ( pAct == NULL) { /* my_log("Error: No Policy for this query(from %s for name:%s) \n", sock_ntop((SA*) &(pQuery->client_addr), sizeof(SA), strAddr, sizeof(strAddr)), pQuery->qname); */ //query_free(pQuery); //queries.queries[num]=NULL; querylist_free_item(&queries,num); } if( pAct->op == Drop) { /* my_log("Dropped query(from %s for name:%s) \n", sock_ntop((SA*) &(pQuery->client_addr), sizeof(SA), strAddr, sizeof(strAddr)), pQuery->qname); */ //query_free(pQuery); //queries.queries[num]=NULL; querylist_free_item(&queries,num); } else if ( pAct->op == Forward || pAct->op == Refuse || pAct->op == Redirect ) { pQuery->status = dispatched; pQuery->resolver = pAct->resolver; pQuery->op = pAct->op; //notify the recv_send that this query is ready for forwarding sendto( listenfd, (char *) &num, sizeof(num), 0, (SA*)&client_addr, addrLen); //debug("Policy lookup finished for %d: %s \n", num, pQuery->qname ); } } //IF(ISSET() } //for(;;) debug("Dispatcher thread[%d] will exit...\n", index); pthread_exit(NULL); }
void JavaExecuter::run() { init(); std::string workingDir = combineString(Config::getInstant()->getTmpUserPath(), DIR_SEPARTOR, runId); int port = 0, status; int server_sock = CreateServerSocket(&port); struct sockaddr_un un; socklen_t len = sizeof(un); if(server_sock < 0) { BLOG("JavaExecuter::run(): create server sock error", SYSCALL_ERROR); this->_result = SERVER_ERROR; return; } pid_t pid = fork(); if(pid < 0) { BLOG("JavaExecuter::run() fork error", SYSCALL_ERROR); this->_result = SERVER_ERROR; return; } if(pid == 0) { close(server_sock); if(chdir(workingDir.c_str()) == -1) { LLOG("Fail to change working dir to " + workingDir, SYSCALL_ERROR); raise(SIGKILL); return; } std::string rootPath = Config::getInstant()->getRootPath(); if(stdinFileName[0] != '/' && stdinFileName[0] != '.') { stdinFileName = rootPath + stdinFileName; } if(stdoutFileName[0] != '/' && stdoutFileName[0] != '/') { stdoutFileName = rootPath + stdoutFileName; } std::string minMem = combineString("-Xms", limitMemory / 2 + 200, 'k'); std::string maxMem = combineString("-Xmx", limitMemory + 200, 'k'); std::string javaLib = combineString("-Djava.library.path=", rootPath, "bin"); std::string jarPath = combineString(rootPath, "bin/JavaSandbox.jar"); std::string portStr = combineString(port); std::string limitTimeStr = combineString(limitTime); std::string limitMemoryStr = combineString(limitMemory); std::string limitOutputStr = combineString(limitOutput); std::string uidStr = combineString(Config::getInstant()->getJobUID()); std::string gidStr = combineString(Config::getInstant()->getJobGID()); for(int i = 0; i < 100; i++) close(i); execlp("java", minMem.c_str(), maxMem.c_str(), javaLib.c_str(), "-jar", jarPath.c_str(), portStr.c_str(), limitTimeStr.c_str(), limitMemoryStr.c_str(), limitOutputStr.c_str(), uidStr.c_str(), gidStr.c_str(), stdinFileName.c_str(), stdoutFileName.c_str(), NULL); LLOG("JavaExecuter()::run() Fail to run java", SYSCALL_ERROR); exit(-1); } else { //parent while(1) { //the accept function will be interuppted by the SIGCHLD signal int client_sock = accept(server_sock, (struct sockaddr*)&un, &len); if(client_sock < 0) { if(errno != EINTR) { BLOG("JavaExecuter::run() fail to accept", SYSCALL_ERROR); close(server_sock); this->_result = SERVER_ERROR; return; }else if(waitpid(pid, &status, WNOHANG) > 0) { break; } } else { unsigned int _time, _memory; while(ReadUint32(client_sock, &_time) >= 0 && ReadUint32(client_sock, &_memory) >= 0) { this->_runnedTime = _time; this->_runnedMemory = _memory; judgeThread->updateRunInfo(_time, _memory); } close(client_sock); while(waitpid(pid, &status, 0) < 0 && errno != ECHILD) { } break; } } close(server_sock); if(WIFSIGNALED(status)) { switch(WTERMSIG(status)) { case SIGXCPU: this->_result = TIME_LIMIT_EXCEEDED; break; default: DLOG(ERROR) << "Java process was terminated by signal " << WTERMSIG(status); this->_result = RUNTIME_ERROR; } } else { this->_result = WEXITSTATUS(status); if(this->_result == 1) { this->_result = SERVER_ERROR; }else{ if(this->_result) this->_result += 1000; } if(this->_result == 0) { this->_result = TraceProcess::NORMAL; if(this->_runnedMemory > limitMemory) { this->_result = MEMORY_LIMIT_EXCEEDED; } if(this->_runnedTime > limitTime) { this->_result = TIME_LIMIT_EXCEEDED; } } } } }