CEDClient* CEDClients::Connect(DWORD nClientID, WORD nClientPort, IN_ADDR* pServerAddress, WORD nServerPort, const Hashes::Guid& oGUID) { CEDClient* pClient = NULL; { CQuickLock oLock( m_pSection ); if ( oGUID ) { pClient = GetByGUID( oGUID ); if ( pClient ) return pClient; } if ( IsFull() ) return NULL; if ( CEDPacket::IsLowID( nClientID ) ) { if ( pServerAddress == NULL || nServerPort == 0 ) return NULL; pClient = GetByID( nClientID, pServerAddress, oGUID ); } else { if ( Security.IsDenied( (IN_ADDR*)&nClientID ) ) return NULL; pClient = GetByID( nClientID, NULL, oGUID ); } } if ( pClient == NULL ) { pClient = new CEDClient(); pClient->ConnectTo( nClientID, nClientPort, pServerAddress, nServerPort, oGUID ); } return pClient; }
int main() { int d; char pilihan; Stack S; CreateEmpty(&S); printf("%d %d\n",S.TOP,S.T[S.TOP]); PrintStack(S); while (!IsFull(S)) { scanf("%c %d",&pilihan,&d); if (pilihan =='p') Pop(&S,d); else if (pilihan == 'h') Push(&S,d); PrintStack(S); printf("%d\n",S.TOP); } return 0; }
int PushData(const void* pdata,size_t szlen,size_t &szconlen) { if (IsFull()) { if (__Throw() == -1) { szconlen = 0; return -1; } } memcpy(__m_pArray[__m_nTail].pData,pdata,szlen); __m_pArray[__m_nTail].szLen = szlen; __m_nTail = (__m_nTail + 1) % (__m_nCapacity + 1); szconlen = (__m_nTail + 1 + __m_nCapacity - __m_nHead) % (__m_nCapacity + 1); return 0; }
int main(){ /*kamus*/ Stack S; address i; infotype x; /*algoritma*/ CreateEmpty(&S); /*mengisi nilai s*/ printf("masukkan isi stack:\n"); while(!IsFull(S)) { scanf("%d",&x); if(x==999) break; Push(&S,x); } TulisStack(S); FilterStack(&S); printf("\nSetelah dibuang bilangan ganjil:\n"); TulisStack(S); return 0; }
int CBufQueue::Enqueue(const char *buffer,unsigned int len) { if (_header == NULL || _data == NULL || len > _header->iBufSize) { return -1; } if(IsFull(len)) { return 0; } // 长度字段被分段 if(_header->iEnd+sizeof(unsigned int)-1 >= _header->iBufSize) { char tmp[4]; SetLen(tmp, len); unsigned len_in_tail_size = _header->iBufSize - _header->iEnd; unsigned len_in_head_size = sizeof(unsigned int) - len_in_tail_size; memcpy(&_data[_header->iEnd], tmp, len_in_tail_size); memcpy(_data, &tmp[len_in_tail_size], len_in_head_size); memcpy(_data+len_in_head_size, buffer, len); _header->iEnd = len_in_head_size + len; if (_header->iEnd+ReserveLen > _header->iBegin) return -1; } // 数据被分段 else if(_header->iEnd+sizeof(unsigned int)+len > _header->iBufSize){ unsigned data_in_tail_size = _header->iBufSize-_header->iEnd-sizeof(unsigned int); SetLen(_data+_header->iEnd,len); memcpy(_data+_header->iEnd+sizeof(unsigned int),buffer,data_in_tail_size); memcpy(_data,buffer+data_in_tail_size,len-data_in_tail_size); _header->iEnd = len-data_in_tail_size; if (_header->iEnd+ReserveLen > _header->iBegin) return -1; } else { SetLen(_data+_header->iEnd,len); memcpy(_data+_header->iEnd+sizeof(unsigned int),buffer,len); _header->iEnd = (_header->iEnd+sizeof(unsigned int)+len)%_header->iBufSize; } return len; }
ValueT* Push(KeyT key) { if(IsFull()) return NULL; size_t curIndex = m_Head->ElementCount++; while(curIndex > 0) { if(CompareT::Compare(m_NodeBuffer[ParentIndex(curIndex)].Key, key) < 0) { m_NodeBuffer[curIndex] = m_NodeBuffer[ParentIndex(curIndex)]; curIndex = ParentIndex(curIndex); } else { m_NodeBuffer[curIndex].Key = key; return &m_NodeBuffer[curIndex].Value; } } m_NodeBuffer[0].Key = key; return &m_NodeBuffer[0].Value; }
bool OctreeNodeQueue::Insert(OctreeNode* node) { // Check if queue is full if (IsFull() == true) { return false; } // If end reaches end of array, set it to beginning if (++_back == _maximumSize) { _back = 0; } // Set node in queue _array[_back] = node; // Increment size _currentSize++; // Return return true; }
int RingBuffer::Write(const void* source, int length) { assert(m_buffer); assert(source); assert(length >= 0); assert(m_writeBytesAvailable >= 0); // If there is no space or nothing to write then don't do anything. if (IsFull() || length == 0) return 0; // Clamp the length to the number of bytes available for writing. if (length > m_writeBytesAvailable) length = m_writeBytesAvailable; int remainingWriteBytes = m_sizeBytes - m_writeIndex; if (length > remainingWriteBytes) { // If the number of bytes to write is bigger than the remaining bytes // in the buffer, we have to wrap around and write into two regions. memcpy(m_buffer + m_writeIndex, source, remainingWriteBytes); memcpy(m_buffer, (char*)source + remainingWriteBytes, length - remainingWriteBytes); } else { // No wrapping, only one region to write to, which starts from the write index. memcpy(m_buffer + m_writeIndex, source, length); } // Increment the write index and wrap around at the end. m_writeIndex = (m_writeIndex + length) % m_sizeBytes; // Update the read and write sizes. m_writeBytesAvailable -= length; m_readBytesAvailable += length; return length; }
void Enqueue(Queue Q, ElementType Value) { ElementType *Buffer; int i; if (IsFull(Q)) { Buffer = malloc(sizeof(ElementType) * Q -> Capacity * 2); i = 0; while (!IsEmpty(Q)) Buffer[i++] = Dequeue(Q); Q -> Front = 0; Q -> Rear = i; Q -> Capacity *= 2; free(Q -> Next); Q -> Next = Buffer; } Q -> Next[Q -> Rear] = Value; Q -> Rear = Succ(Q, Q -> Rear); return; }
void QueueType<ItemType>::Enqueue(ItemType i) { if(IsFull()) { throw FullQueue(); } else { NodeType<ItemType> *location; location = new NodeType<ItemType>; location->info = i; location->next = NULL; if(rear == NULL) front = location; else rear->next = location; rear = location; } }
void QueType::Enqueue(ItemType newItem) // Adds newItem to the rear of the queue. // Pre: Queue has been initialized. // Post: If (queue is not full) newItem is at the rear of the queue; // otherwise a FullQueue exception is thrown. { if (IsFull()) throw FullQueue(); else { NodeType* newNode; newNode = new NodeType; newNode->info = newItem; newNode->next = NULL; if (rear == NULL) front = newNode; else rear->next = newNode; rear = newNode; } }
void Add1Urut (TabInt *T, ElType X) { /* Kamus */ IdxType i,j; boolean pas=false; /* Algoritma */ if (IsEmpty(*T)) { SetEl(T,1,X); } else if (!IsFull(*T)) { i=GetFirstIdx(*T); j=GetLastIdx(*T); if (NbElmt(*T)!=1) { while ((i<=j)&&(!pas)) { if (GetElmt(*T,i)>=X) { pas=true; } else { i++; } } while (j>=i) { if (j>i) { SetEl(T,j+1,GetElmt(*T,j)); } else { SetEl(T,j+1,GetElmt(*T,j)); SetEl(T,j,X); } j--; } } else { if (GetElmt(*T,i)<=X) { SetEl(T,i+1,GetElmt(*T,i)); SetEl(T,i,X); } else { SetEl(T,i+1,X); } } } }
bool CDBTemplateStruct::RegInt( BOOL Primary, const char* pName, BOOL NewColumn, int Default, BOOL IsUnsigned, BOOL IsIndex, BOOL IsEncrypt, const char* pEnctyptKey ) { if (FindColumn(pName)) { Assert(false); return false; } if (IsFull() && !_Resize()) { Assert(false); return false; } ColumnInfo& ci = m_pColumnInfo[m_ColumnInfoCount]; ci.m_Type = EM_TYPE_DB_COLUMN_INT; ci.m_Len = sizeof(int); ci.m_Pos = m_CurOffset; ci.m_Primary = Primary; ci.m_IsUnsigned = IsUnsigned; ci.m_NewColumn = NewColumn; ci.m_pTemplate = 0; ci.m_IsIndex = IsIndex; ci.m_IsEncrypt = IsEncrypt; CTools::Strcpy(ci.m_Name, pName, sizeof(ci.m_Name)); std::string strName = pName; m_HashColumnInfo[strName] = &ci; if (IsEncrypt) { CTools::Strcpy(ci.m_EncryptKey, pEnctyptKey, sizeof(ci.m_EncryptKey)); } ci.m_DefaultLen = sizeof(Default); memcpy(ci.m_Default, &Default, ci.m_DefaultLen); CTools::Strcpy(ci.m_ColumnDefault, DB_SQL_FORMAT_DEFAULT_INT, sizeof(ci.m_ColumnDefault)); m_CurOffset += (int)sizeof(int); m_ColumnInfoCount++; }
int main() { int M,N,K; int i,j; int temp,flag; scanf ("%d %d %d", &M, &N, &K); for (j=0; j<K; j++){ CreateStack(M); int X; temp = 1; flag = 1; for (i=0; i<N; i++){ scanf ("%d", &X); while (1){ if (IsEmpty()||TopNum()!=X){ if (!IsFull()) Push(temp++); else { flag =0; break; } } else if (TopNum() == X){ Pop(); break; } } } if (flag&&IsEmpty()) printf ("YES\n"); else printf ("NO\n"); } return 0; }
BOOL CEDClients::OnAccept(CConnection* pConnection) { ASSERT( pConnection != NULL ); if ( Settings.Connection.RequireForTransfers && ! Settings.eDonkey.EnableToday ) { theApp.Message( MSG_ERROR, IDS_ED2K_CLIENT_DISABLED, (LPCTSTR)pConnection->m_sAddress ); return FALSE; } CSingleLock pLock( &Transfers.m_pSection ); if ( ! pLock.Lock( 250 ) ) return FALSE; if ( IsFull() ) { // Even if we're full, we still need to accept connections from clients we have queued, etc if ( ( GetByIP( &pConnection->m_pHost.sin_addr ) == NULL ) || ( IsOverloaded() ) ) { theApp.Message( MSG_DEBUG, _T("Rejecting ed2k connection from %s, max client connections reached."), (LPCTSTR)pConnection->m_sAddress ); return FALSE; } else { theApp.Message( MSG_DEBUG, _T("Accepting ed2k connection from %s despite client connection limit."), (LPCTSTR)pConnection->m_sAddress ); } } CEDClient* pClient = new CEDClient(); pClient->AttachTo( pConnection ); return TRUE; }
static int TreeAddSymbol(HuffmanTree* const tree, int symbol, int code, int code_length) { HuffmanTreeNode* node = tree->root_; const HuffmanTreeNode* const max_node = tree->root_ + tree->max_nodes_; while (code_length-- > 0) { if (node >= max_node) { return 0; } if (NodeIsEmpty(node)) { if (IsFull(tree)) return 0; // error: too many symbols. AssignChildren(tree, node); } else if (HuffmanTreeNodeIsLeaf(node)) { return 0; // leaf is already occupied. } node += node->children_ + ((code >> code_length) & 1); } if (NodeIsEmpty(node)) { node->children_ = 0; // turn newly created node into a leaf. } else if (!HuffmanTreeNodeIsLeaf(node)) { return 0; // trying to assign a symbol to already used code. } node->symbol_ = symbol; // Add symbol in this node. return 1; }
void Counter::Tick(DWORD times) { m_dwElapseTime += times; if (IsFull()) Stop(); }
void NoximBuffer::Push(const NoximFlit & flit) { if (IsFull()) Drop(flit); else buffer.push(flit); }
void Stack::Push(int value) { if (IsFull()) Grow(); data[++top] = value; }
//Inserts a character into the buffer. void CConsole::InsertChar(const int szChar, const wchar_t cooked) { static int iHistoryPos = -1; if (!m_bVisible) return; switch (szChar) { case SDLK_RETURN: iHistoryPos = -1; m_iMsgHistPos = 1; ProcessBuffer(m_szBuffer); FlushBuffer(); return; case SDLK_TAB: // Auto Complete return; case SDLK_BACKSPACE: if (IsEmpty() || IsBOB()) return; if (m_iBufferPos == m_iBufferLength) m_szBuffer[m_iBufferPos - 1] = '\0'; else { for (int j = m_iBufferPos-1; j < m_iBufferLength-1; j++) m_szBuffer[j] = m_szBuffer[j+1]; // move chars to left m_szBuffer[m_iBufferLength-1] = '\0'; } m_iBufferPos--; m_iBufferLength--; return; case SDLK_DELETE: if (IsEmpty() || IsEOB()) return; if (m_iBufferPos == m_iBufferLength-1) { m_szBuffer[m_iBufferPos] = '\0'; m_iBufferLength--; } else { if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL]) { // Make Ctrl-Delete delete up to end of line m_szBuffer[m_iBufferPos] = '\0'; m_iBufferLength = m_iBufferPos; } else { // Delete just one char and move the others left for(int j=m_iBufferPos; j<m_iBufferLength-1; j++) m_szBuffer[j] = m_szBuffer[j+1]; m_szBuffer[m_iBufferLength-1] = '\0'; m_iBufferLength--; } } return; case SDLK_HOME: if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL]) { CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory int linesShown = (int)m_fHeight/m_iFontHeight - 4; m_iMsgHistPos = clamp((int)m_deqMsgHistory.size() - linesShown, 1, (int)m_deqMsgHistory.size()); } else { m_iBufferPos = 0; } return; case SDLK_END: if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL]) { m_iMsgHistPos = 1; } else { m_iBufferPos = m_iBufferLength; } return; case SDLK_LEFT: if (m_iBufferPos) m_iBufferPos--; return; case SDLK_RIGHT: if (m_iBufferPos != m_iBufferLength) m_iBufferPos++; return; // BEGIN: Buffer History Lookup case SDLK_UP: if (m_deqBufHistory.size() && iHistoryPos != (int)m_deqBufHistory.size() - 1) { iHistoryPos++; SetBuffer(m_deqBufHistory.at(iHistoryPos).c_str()); m_iBufferPos = m_iBufferLength; } return; case SDLK_DOWN: if (m_deqBufHistory.size()) { if (iHistoryPos > 0) { iHistoryPos--; SetBuffer(m_deqBufHistory.at(iHistoryPos).c_str()); m_iBufferPos = m_iBufferLength; } else if (iHistoryPos == 0) { iHistoryPos--; FlushBuffer(); } } return; // END: Buffer History Lookup // BEGIN: Message History Lookup case SDLK_PAGEUP: { CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory if (m_iMsgHistPos != (int)m_deqMsgHistory.size()) m_iMsgHistPos++; return; } case SDLK_PAGEDOWN: if (m_iMsgHistPos != 1) m_iMsgHistPos--; return; // END: Message History Lookup default: //Insert a character if (IsFull()) return; if (cooked == 0) return; if (IsEOB()) //are we at the end of the buffer? m_szBuffer[m_iBufferPos] = cooked; //cat char onto end else { //we need to insert int i; for(i=m_iBufferLength; i>m_iBufferPos; i--) m_szBuffer[i] = m_szBuffer[i-1]; // move chars to right m_szBuffer[i] = cooked; } m_iBufferPos++; m_iBufferLength++; return; } }
void TBalanceTree::InsRecord(TKey k, PTDatValue pVal) { // вставить запись if (IsFull()) SetRetCode(TabFull); else InsBalanceTree((PTBalanceNode&)pRoot, k, pVal); }
/** add (allocate), but don't construct item */ FORCEINLINE Titem& AddNC() { assert(!IsFull()); return m_items[SizeRef()++]; }
void Stack<T>::Push(const T & item) { // NEED TO IMPLEMENT if (!(IsFull())) stack[++top] = item; }
int main() { ArrayStack s; ElementType i; ElementType tmp; s = CreateArrayStack(10); printf("Print Stack: "); PrintArrayStack(s); if(IsEmpty(s)) { printf("\nEmpty stack.\n"); } if(IsFull(s)) { printf("\nFull stack.\n"); } printf("\n\n"); for(i = 0; i < 10; i++) { printf("Push %d into stack. \n", i); Push(i, s); } printf("\n\n"); printf("Print Stack: "); PrintArrayStack(s); printf("Top of stack: %d\n", Top(s)); if(IsEmpty(s)) { printf("\nEmpty stack.\n"); } if(IsFull(s)) { printf("\nFull stack.\n"); } printf("\n\n"); for(i = 0; i < 5; i++){ tmp = TopAndPop(s); printf("Top of stack: %d\n", tmp); printf("Pop out of stack: %d\n", tmp); } printf("\n\n"); printf("Print Stack: "); PrintArrayStack(s); if(IsEmpty(s)) { printf("\nEmpty stack.\n"); } if(IsFull(s)) { printf("\nFull stack.\n"); } printf("Top of stack: %d\n", Top(s)); printf("\n\nMake Empty Stack!\n"); MakeEmpty(s); if(IsEmpty(s)) { printf("\nEmpty stack.\n"); } if(IsFull(s)) { printf("\nFull stack.\n"); } DisposeArrayStack(s); return 0; }
/** add (allocate), but don't construct item */ inline T *Append() { assert(!IsFull()); return &data[SizeRef()++]; }
bool Group::_addMember(ObjectGuid guid, const char* name, bool isAssistant, uint8 group) { if (IsFull()) return false; if (!guid) return false; Player* player = sObjectMgr.GetPlayer(guid, false); uint32 lastMap = 0; if (player && player->IsInWorld()) lastMap = player->GetMapId(); else if (player && player->IsBeingTeleported()) lastMap = player->GetTeleportDest().mapid; MemberSlot member; member.guid = guid; member.name = name; member.group = group; member.assistant = isAssistant; member.lastMap = lastMap; m_memberSlots.push_back(member); SubGroupCounterIncrease(group); if (player) { player->SetGroupInvite(nullptr); // if player is in group and he is being added to BG raid group, then call SetBattleGroundRaid() if (player->GetGroup() && isBGGroup()) player->SetBattleGroundRaid(this, group); // if player is in bg raid and we are adding him to normal group, then call SetOriginalGroup() else if (player->GetGroup()) player->SetOriginalGroup(this, group); // if player is not in group, then call set group else player->SetGroup(this, group); if (player->IsInWorld()) { // if the same group invites the player back, cancel the homebind timer if (InstanceGroupBind* bind = GetBoundInstance(player->GetMapId(), player)) if (bind->state->GetInstanceId() == player->GetInstanceId()) player->m_InstanceValid = true; } } if (!isRaidGroup()) // reset targetIcons for non-raid-groups { for (int i = 0; i < TARGET_ICON_COUNT; ++i) m_targetIcons[i].Clear(); } if (!isBGGroup()) { // insert into group table CharacterDatabase.PExecute("INSERT INTO group_member(groupId,memberGuid,assistant,subgroup) VALUES('%u','%u','%u','%u')", m_Id, member.guid.GetCounter(), ((member.assistant == 1) ? 1 : 0), member.group); } return true; }
VOID FxWakeInterruptMachine::ProcessEvent( __in FxWakeInterruptEvents Event ) { NTSTATUS status; KIRQL irql; LONGLONG timeout = 0; // // Acquire state machine *queue* lock, raising to DISPATCH_LEVEL // Lock(&irql); if (IsFull()) { // // The queue is full. This should never happen. // Unlock(irql); ASSERTMSG("The wake interrupt state machine queue is full\n", FALSE); return; } if (IsClosedLocked()) { // // The queue is closed. This should never happen. // DoTraceLevelMessage( m_PkgPnp->GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNP, "WDFDEVICE 0x%p !devobj 0x%p current wake interrupt state" " %!FxWakeInterruptStates! dropping event " "%!FxWakeInterruptEvents! because of a closed queue", m_PkgPnp->GetDevice()->GetHandle(), m_PkgPnp->GetDevice()->GetDeviceObject(), m_CurrentState, Event); Unlock(irql); ASSERTMSG( "The wake interrupt state machine queue is closed\n", FALSE ); return; } // // Enqueue the event // m_Queue[InsertAtTail()] = Event; // // Drop the state machine *queue* lock // Unlock(irql); // // Now, if we are running at PASSIVE_LEVEL, attempt to run the state machine // on this thread. If we can't do that, then queue a work item. // if (irql == PASSIVE_LEVEL) { // // Try to acquire the state machine lock // status = m_StateMachineLock.AcquireLock( m_PkgPnp->GetDriverGlobals(), &timeout ); if (FxWaitLockInternal::IsLockAcquired(status)) { FxPostProcessInfo info; // // We now hold the state machine lock. So call the function that // dispatches the next state. // ProcessEventInner(&info); // // The pnp state machine should be the only one deleting the object // ASSERT(info.m_DeleteObject == FALSE); // // Release the state machine lock // m_StateMachineLock.ReleaseLock( m_PkgPnp->GetDriverGlobals() ); info.Evaluate(m_PkgPnp); return; } } // // For one reason or another, we couldn't run the state machine on this // thread. So queue a work item to do it. // QueueToThread(); return; }
bool My_Q:: BreakCondition() { return(IsFull()&&(container[r]-container[f]<threshold)); }
void CachedInterpreter::Jit(u32 address) { if (m_code.size() >= CODE_SIZE / sizeof(Instruction) - 0x1000 || IsFull() || SConfig::GetInstance().bJITNoBlockCache) { ClearCache(); } u32 nextPC = analyzer.Analyze(PC, &code_block, &code_buffer, code_buffer.GetSize()); if (code_block.m_memory_exception) { // Address of instruction could not be translated NPC = nextPC; PowerPC::ppcState.Exceptions |= EXCEPTION_ISI; PowerPC::CheckExceptions(); WARN_LOG(POWERPC, "ISI exception at 0x%08x", nextPC); return; } int block_num = AllocateBlock(PC); JitBlock *b = GetBlock(block_num); js.blockStart = PC; js.firstFPInstructionFound = false; js.fifoBytesThisBlock = 0; js.downcountAmount = 0; js.curBlock = b; PPCAnalyst::CodeOp *ops = code_buffer.codebuffer; b->checkedEntry = GetCodePtr(); b->normalEntry = GetCodePtr(); b->runCount = 0; for (u32 i = 0; i < code_block.m_num_instructions; i++) { js.downcountAmount += ops[i].opinfo->numCycles; u32 function = HLE::GetFunctionIndex(ops[i].address); if (function != 0) { int type = HLE::GetFunctionTypeByIndex(function); if (type == HLE::HLE_HOOK_START || type == HLE::HLE_HOOK_REPLACE) { int flags = HLE::GetFunctionFlagsByIndex(function); if (HLE::IsEnabled(flags)) { m_code.emplace_back(WritePC, ops[i].address); m_code.emplace_back(Interpreter::HLEFunction, ops[i].inst); if (type == HLE::HLE_HOOK_REPLACE) { m_code.emplace_back(EndBlock, js.downcountAmount); m_code.emplace_back(); break; } } } } if (!ops[i].skip) { if ((ops[i].opinfo->flags & FL_USE_FPU) && !js.firstFPInstructionFound) { m_code.emplace_back(CheckFPU, ops[i].address); js.firstFPInstructionFound = true; } if (ops[i].opinfo->flags & FL_ENDBLOCK) m_code.emplace_back(WritePC, ops[i].address); m_code.emplace_back(GetInterpreterOp(ops[i].inst), ops[i].inst); if (ops[i].opinfo->flags & FL_ENDBLOCK) m_code.emplace_back(EndBlock, js.downcountAmount); } } if (code_block.m_broken) { m_code.emplace_back(WritePC, nextPC); m_code.emplace_back(EndBlock, js.downcountAmount); } m_code.emplace_back(); b->codeSize = (u32)(GetCodePtr() - b->checkedEntry); b->originalSize = code_block.m_num_instructions; FinalizeBlock(block_num, jo.enableBlocklink, b->checkedEntry); }
int main(int argc, char * argv[]) { int policy; /* replacement policy */ int current; /* current page accessed */ FILE * fp; /* The file containing the page accesses */ FILE * rp; /* output file */ char filename[30]={""}; const char * extension[] ={".fifo", ".lru", "new"}; float num_accesses = 0.0; /* total number of page accesses */ float page_faults = 0.0; unsigned victim = 0; /* page to be replaced */ /* Getting and checking the input from the command line */ if(argc != 4) { printf("usage: pager policy size filename\n"); exit(1); } policy = atoi(argv[1]); mem_size = atoi(argv[2]); if( policy < 0 || policy > 2) { printf("policy must be 0, 1, or 2\n"); exit(1); } if(mem_size <= 0 ) { printf("Size must be a positive integer.\n"); exit(1); } /* Allocate and initialize the memory */ mem = (int *)calloc(mem_size, sizeof(int)); if(!mem) { printf("Cannot allocate mem\n"); exit(1); } /* open the memory access file */ fp = fopen(argv[3], "r"); if(!fp) { printf("Cannot open file %s\n", argv[3]); exit(1); } /* Create the output file */ strcat(filename, argv[3]); strcat(filename,extension[policy]); rp = fopen(filename, "w"); if(!rp) { printf("Cannot create file %s\n", filename); exit(1); } /* The main loop of the program */ fscanf(fp,"%d", ¤t); while(!feof(fp)) { num_accesses++; if(mem_check(current) == PAGEMISS) page_faults++; switch(policy) { case 0: if( IsFull()) { victim = fifo(); mem[victim] = current; } else insert(current); break; case 1: if( IsFull()) { victim = lru(); mem[victim] = current; } else insert(current); break; case 2: if( IsFull()) { victim = own(); mem[victim] = current; } else insert(current); break; default: printf("Unknown policy ... Exiting\n"); exit(1); }/* end switch-case */ print_mem(rp); fscanf(fp,"%d", ¤t); }/* end while */ fprintf(rp,"percentage of page faults = %f", page_faults/num_accesses); /* wrap-up */ fclose(fp); fclose(rp); free(mem); return 1; }