Exemple #1
0
bool ListProcesses(NamedPipe& pipe, CmdMessage& cmd)
{
    ListMessage msg;
    Read(pipe,&msg,sizeof(msg));

    if(!pipe.ImpersonateClient())
        throw win32::SystemError(L"Impersonate client failed");

    ThreadToken token(TOKEN_ADJUST_PRIVILEGES);
    if(!token.AdjustPrivilege(SE_DEBUG_NAME,true))
        throw win32::SystemError(L"Could not do SE_DEBUG_NAME");
    
    ProcessList procs;
    if(msg.hasPid())
        procs.add(msg.GetPid());
    else
        procs.add(msg.GetPath());

    for(ProcessList::iterator it=procs.begin();it!=procs.end();it++)
    {
        ProcessParams param(*it);
        ListResult res(param.GetPid(),param.GetParent(),param.GetSession(),param.GetApplicationName(),param.GetCommandLine(),param.GetCurrentDirectory());

        Overlapped ovl;
        if(!pipe.Write(&res,sizeof(res),&ovl) && !Complete(ovl,clienttimeout))
            throw win32::SystemError(L"Could not send result to the client");
    }
    return true;
}
Exemple #2
0
int main(int argc, char const *argv[])
{
	std::fstream f;
	f.open("test.txt");
	if(!f)
		std::cout << "open file fail" << std::endl;;

	JobList job;
	ProcessList process;
	PCB cur_process;
	unsigned int time = 0;

	job.init(f);
	while(1)
	{
		job.schedule(process,time);
		if(process.schedule(cur_process))
		{
			cur_process.running(time);
			std::cout << "running" << std::endl;
		}
		else
		{
			std::cout << "no running" << std::endl;
		}
		time++;
	}
	f.close();
	return 0;
}
Exemple #3
0
//! \brief Setup up for our basis.
//! \details Bases with the same size is collapsed to one, while different sized bases are appended
//! \param plist The process list with bases and fields
//! \param level The file level to load bases from
//! \param hdf The HDF5 file reader to use
//! \param dims The dimensionality of the basis
//! \param n The number of points in each direction per knot span in the tesselation
//! \param vtf The VTF/VTU file to write to
//! \param block Running VTF block counter
//! \param vtflevel The time level / load case in the VTF file
PatchMap setupPatchMap(const ProcessList& plist, int level, HDF5Writer& hdf, int dims, int* n,
                       VTF& vtf, int& block, int vtflevel)
{
  vtf.clearGeometryBlocks();
  int start=1;
  std::map<int, BasisInfo> created;
  PatchMap result;
  for (ProcessList::const_iterator it  = plist.begin();
                                   it != plist.end(); ++it) {
    if (it->first == "nodalforces")
      continue;
    readBasis(result[it->first].Patch, it->second[0].basis, it->second[0].patches, hdf, dims, level);
    std::map<int, BasisInfo>::iterator loc = created.find(it->second[0].patches);
    // tesselate some more patches
    if (loc == created.end()) {
      generateFEModel(created[it->second[0].patches].FakeModel, result[it->first].Patch, dims, n);
      loc = created.find(it->second[0].patches);
      loc->second.StartPart = start;
      for (size_t l=0;l<result[it->first].Patch.size();++l)
        writePatchGeometry(result[it->first].Patch[l], start+l, vtf, n, ++block);
      start += it->second[0].patches;
    }

    result[it->first].StartPart = loc->second.StartPart;
    result[it->first].FakeModel = loc->second.FakeModel;
  }

  return result;
}
Exemple #4
0
// *****************************************************************************
void cHumanView::SetSFXVolume()
{
	ProcessList pProcessList;
	m_pGame->VGetProcessManager()->VGetProcesses(m_hashSFXChannel, pProcessList);
	ProcessList::iterator curProcess;
	for (curProcess = pProcessList.begin(); curProcess != pProcessList.end(); curProcess++)
	{
		shared_ptr<ISoundProcess> p = dynamic_pointer_cast<ISoundProcess>(*curProcess);
		p->VSetVolume(cGameOptions::GameOptions().iSFXVolume);
	}
}
Exemple #5
0
// *******************************************************************************************
void cBreakoutView::VRenderPrivate()
{
	ProcessList pProcessList;
	m_pGame->VGetProcessManager()->VGetProcesses(cRenderSystem::m_Type, pProcessList);
	for (auto curProcess = pProcessList.begin(); curProcess != pProcessList.end(); curProcess++)
	{
		shared_ptr<cRenderSystem> p = dynamic_pointer_cast<cRenderSystem>(*curProcess);
		p->Render(m_pCamera);
	}
	cHumanView::VRenderPrivate();
}
ProcessList QtProcessFinder::search() {
	ProcessList list;

	HANDLE hProcessSnap;
	HANDLE hProcess;
	PROCESSENTRY32 pe32;
	DWORD dwPriorityClass;

	// Take a snapshot of all processes in the system.
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnap == INVALID_HANDLE_VALUE) {
		qFatal("CreateToolhelp32Snapshot (of processes)");
		return list;
	}

	// Set the size of the structure before using it.
	pe32.dwSize = sizeof(PROCESSENTRY32);

	// Retrieve information about the first process,
	// and exit if unsuccessful
	if (!Process32First(hProcessSnap, &pe32)) {
		qFatal("Process32First");  // show cause of failure
		CloseHandle(hProcessSnap); // clean the snapshot object
		return list;
	}

	// Now walk the snapshot of processes, and
	// display information about each process in turn
	do {
		// Skip the system idle process
		if (pe32.th32ProcessID == 0) continue;

		// Retrieve the priority class.
		dwPriorityClass = 0;
		hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
		if (hProcess == NULL)
			qDebug("OpenProcess");
		else {
			dwPriorityClass = GetPriorityClass(hProcess);
			if (!dwPriorityClass) qDebug("GetPriorityClass");
			CloseHandle(hProcess);
		}

		// List the modules and threads associated with this process
		if (processUsesQt(pe32.th32ProcessID)) {
			list.push_back(Process(pe32.th32ProcessID, QString::fromStdWString(pe32.szExeFile)));
		}

	} while (Process32Next(hProcessSnap, &pe32));

	CloseHandle(hProcessSnap);
	return list;
}
Exemple #7
0
void terminateAllRunningKDEProcesses(ProcessList &processList)
{
    QString installPrefix = QStringLiteral(CMAKE_INSTALL_PREFIX);

    foreach (const ProcessListEntry *ple, processList.list()) {
        if (!ple->path.isEmpty() && ple->path.toLower().startsWith(installPrefix.toLower())) {
            if (verbose) {
                fprintf(stderr, "terminating path: %s name: %s pid: %u\n", ple->path.toLatin1().data(), ple->name.toLatin1().data(), ple->pid);
            }
            processList.terminateProcess(ple->name);
        }
    }
}
Exemple #8
0
bool JobList::schedule(ProcessList &p,unsigned int time)
{
	if(hasJob() == false)
		return false;
	auto min = jlist.begin();
	bool sign = false;
	for(auto i = min; i != jlist.end(); ++i)
	{
		unsigned int m = getUnusedMem();
		if(i->stime <= time  && i->memory <= m)
		{
			if(i->ntime <= min->ntime || min->memory > m)
			{
				min = i;
				sign = true;
			}
		}
	}

	if(!sign)
		return false;

	if(NULL == ( min->memAddr = mm_malloc(min->memory)))
		return false;

	p.insertJobB(*min);	
	jlist.erase(min);
	return true;
}
Exemple #9
0
void LogFile::writeProcessList(const ProcessList &processList)
{
    fprintf(m_file, "[");
    bool first = true;
    for (auto i = processList.cbegin(); i != processList.cend(); i++)
    {
        if (!first)
        {
            fprintf(m_file, ",");
        }
        else
        {
            first = false;
        }
        writeProcessRecord(*i);
    }
    fprintf(m_file, "]");
}
Exemple #10
0
int main(int argc, char **argv)
{
    EventList eventlist;
    ProcessList processes;

    long ev_EndSimulation = 0;
    
    Traverser traverser(&eventlist);
    ColdTestCell cell1(&eventlist,&traverser);
    ColdTestCell cell2(&eventlist, &traverser);
    ColdTestCell cell3(&eventlist, &traverser);
    Source supply(&eventlist, &traverser);
    Sink derig(&eventlist);

    processes.push_back(&traverser);
    processes.push_back(&cell1);
    processes.push_back(&cell2);
    processes.push_back(&cell3);
    processes.push_back(&supply);
    processes.push_back(&derig);
    
    // Connect up production layout
    
    traverser.cell1(&cell1);
    traverser.cell2(&cell2);
    traverser.cell3(&cell3);
    traverser.infeed(&supply);
    traverser.outfeed(&derig);

    // Initialise the processes

    eventlist.push(new Event(100000,
                             nullptr,
                             ev_EndSimulation)); // End Simulation Event
    bool change;
    do {
        change = false;
        for (ProcessList::iterator i = processes.begin();
                 i != processes.end(); i++)
            change |= (*i)->run(); // Run each process until no change
    } while (change);


    // Run the event management loop.
    while (Event *event = eventlist.top()) {
        eventlist.pop(); // Remove the top element from the list
        SimulationTime += event->getTime(); // Advance simulation time
        if (event->getEventType() == ev_EndSimulation)
            break;
        event->getProcess()->HandleEvent(event);
        delete event; // no longer needed
    }
}
//  *******************************************************************************************************************
void cProcessManager::VGetProcesses(const cHashedString & Type, ProcessList & pProcessList)
{
	for (auto curProcess = m_pProcessList.begin(); curProcess != m_pProcessList.end(); curProcess++)
	{
		shared_ptr<cProcess> p(*curProcess);
		if(p->VGetType() == Type)
		{
			pProcessList.push_back(p);
		}
	}
}
	ProcessList Process::GetList()
	{
		Handle hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (!hSnapshot.IsValid())
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		PROCESSENTRY32 processEntry = {0};
		processEntry.dwSize = sizeof(processEntry);

		BOOL success = ::Process32First(hSnapshot, &processEntry);
		if (!success)
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		ProcessList list;
		while (success)
		{
#ifdef _DEBUG
			//if (_wcsicmp(processEntry.szExeFile, L"winword.exe") == 0 ||
			//	_wcsicmp(processEntry.szExeFile, L"iexplore.exe") == 0 ||
			//	wcscmp(processEntry.szExeFile, L"firefox.exe") == 0 ||
			//	wcsncmp(processEntry.szExeFile, L"FlashPlayerPlugin", 17) == 0 ||
			//	wcscmp(processEntry.szExeFile, L"AccessEnum.exe") == 0 ||
			//	wcscmp(processEntry.szExeFile, L"TSVNCache.exe") == 0 ||
			//	wcscmp(processEntry.szExeFile, L"plugin-container.exe") == 0)
#endif
			list.push_back(Process(
				processEntry.th32ProcessID,
				processEntry.th32ParentProcessID,
				processEntry.szExeFile));

			success = ::Process32Next(hSnapshot, &processEntry);
		}

		return list;
	}
Exemple #13
0
// *****************************************************************************
void cProcessManager::VGetProcesses(const cString & strType, ProcessList & pProcessList)
{
	ProcessList::iterator curProcess;
	unsigned long hash = cHashedString::CalculateHash(strType);
	for (curProcess = m_pProcessList.begin(); curProcess != m_pProcessList.end(); curProcess++)
	{
		shared_ptr<cProcess> p(*curProcess);
		if(p->m_strType.GetHash() == hash)
		{
			pProcessList.push_back(p);
		}
	}
	
}
Exemple #14
0
bool PCB::running(ProcessList &p,unsigned int time)
{
	rtime++;
	if(rtime == ntime)
	{
		ftime = time;
		turntime = time - stime;
		wtime = (float)(turntime)/ntime;
		state = FINISH;
		tape->release(pid);
		mm_free(memAddr);
	}
	else
	{
        p.insertJobF(*this);
		state = WAIT;

	}
	return true;
}
Exemple #15
0
/**
 * Driver Thread
 * Runs the schedulers and dispatcher.
 */
void* driver_thread(void*) 
{
	Loader loader;
	ProcessList* pList = 0;
	LongTermScheduler* lts = 0;
	ShortTermScheduler* sts = 0;
	Dispatcher* dsp = 0;
	pthread_t cpuThread;
	bool done = false;
	unsigned int ltsCnt = 0;

	disk = new Memory(2048);
	ram = new Memory(1024);

	loader = Loader("data/datafile2.txt");
	pList = loader.loadDisk(disk);

	cpu = new Cpu(ram, pList);

	lts = new LongTermScheduler(disk, ram, pList); // TODO: CPU instead of pList?
	sts = new ShortTermScheduler(cpu);
	dsp = new Dispatcher(cpu, ram);

	if(DEBUGGING) {
		cpu->setDebug(true);
		lts->setDebug(true);
		sts->setDebug(true);
		dsp->setDebug(true);
	}

	// Run the schedulers once at the start
	lts->schedule();
	sts->rebuildQueue();
	dsp->dispatch();
	ltsCnt = 1;

	// Spawn CPU thread. 
	pthread_create(&cpuThread, 0, &cpu_thread, 0);

	do
	{
		done = true;

		// Wait for interrupt. 
		pthread_mutex_lock(&mux);
		pthread_cond_wait(&interrupt, &mux);

		// LTS only runs every so often.
		if(ltsCnt % 4 == 0) {
			lts->schedule();
		}
		ltsCnt++;

		// STS, Dispatcher
		sts->rebuildQueue();
		dsp->dispatch();

		// See if we can stop. 
		for(unsigned int i = 0; i < pList->all.size(); i++) {
			if(pList->all[i]->state != STATE_TERM_UNLOADED) {
				done = false;
				break;
			}
		}

		pthread_mutex_unlock(&mux);
	} 
	while(!done);

	pthread_join(cpuThread, 0);

	// Final Report
	cout << "\nFinal PCB Values:\n";
	cout << "=================\n";
	pList->printJobs();
	cout << endl;

	cout << "Writing memories to disk...\n";
	ram->writeDisk("ram.txt");
	disk->writeDisk("disk.txt");

	return 0;
}
void
Group::detachedProcessesCheckerMain(GroupPtr self) {
	TRACE_POINT();
	Pool *pool = getPool();

	Pool::DebugSupportPtr debug = pool->debugSupport;
	if (debug != NULL && debug->detachedProcessesChecker) {
		debug->debugger->send("About to start detached processes checker");
		debug->messages->recv("Proceed with starting detached processes checker");
	}

	boost::unique_lock<boost::mutex> lock(pool->syncher);
	while (true) {
		assert(detachedProcessesCheckerActive);

		if (getLifeStatus() == SHUT_DOWN || this_thread::interruption_requested()) {
			UPDATE_TRACE_POINT();
			P_DEBUG("Stopping detached processes checker");
			detachedProcessesCheckerActive = false;
			break;
		}

		UPDATE_TRACE_POINT();
		if (!detachedProcesses.empty()) {
			P_TRACE(2, "Checking whether any of the " << detachedProcesses.size() <<
				" detached processes have exited...");
			ProcessList::iterator it, end = detachedProcesses.end();
			ProcessList processesToRemove;

			for (it = detachedProcesses.begin(); it != end; it++) {
				const ProcessPtr process = *it;
				switch (process->getLifeStatus()) {
				case Process::ALIVE:
					if (process->canTriggerShutdown()) {
						P_DEBUG("Detached process " << process->inspect() <<
							" has 0 active sessions now. Triggering shutdown.");
						process->triggerShutdown();
						assert(process->getLifeStatus() == Process::SHUTDOWN_TRIGGERED);
					}
					break;
				case Process::SHUTDOWN_TRIGGERED:
					if (process->canCleanup()) {
						P_DEBUG("Detached process " << process->inspect() << " has shut down. Cleaning up associated resources.");
						process->cleanup();
						assert(process->getLifeStatus() == Process::DEAD);
						processesToRemove.push_back(process);
					} else if (process->shutdownTimeoutExpired()) {
						P_WARN("Detached process " << process->inspect() <<
							" didn't shut down within " PROCESS_SHUTDOWN_TIMEOUT_DISPLAY
							". Forcefully killing it with SIGKILL.");
						kill(process->getPid(), SIGKILL);
					}
					break;
				default:
					P_BUG("Unknown 'lifeStatus' state " << (int) process->getLifeStatus());
				}
			}

			UPDATE_TRACE_POINT();
			end = processesToRemove.end();
			for (it = processesToRemove.begin(); it != end; it++) {
				removeProcessFromList(*it, detachedProcesses);
			}
		}

		UPDATE_TRACE_POINT();
		if (detachedProcesses.empty()) {
			UPDATE_TRACE_POINT();
			P_DEBUG("Stopping detached processes checker");
			detachedProcessesCheckerActive = false;

			boost::container::vector<Callback> actions;
			if (shutdownCanFinish()) {
				UPDATE_TRACE_POINT();
				finishShutdown(actions);
			}

			verifyInvariants();
			verifyExpensiveInvariants();
			lock.unlock();
			UPDATE_TRACE_POINT();
			runAllActions(actions);
			break;
		} else {
			UPDATE_TRACE_POINT();
			verifyInvariants();
			verifyExpensiveInvariants();
		}

		// Not all processes can be shut down yet. Sleep for a while unless
		// someone wakes us up.
		UPDATE_TRACE_POINT();
		detachedProcessesCheckerCond.timed_wait(lock,
			posix_time::milliseconds(100));
	}
}
Exemple #17
0
int main (int argc, char** argv)
{
  int format = 1;
  int n[3] = { 2, 2, 2 };
  int dims = 3;
  int skip=1;
  int start=0;
  int end=-1;
  bool last=false;
  char* infile = 0;
  char* vtffile = 0;
  float starttime = -1, endtime = -1;

  for (int i = 1; i < argc; i++)
    if (!strcmp(argv[i],"-format") && i < argc-1) {
      if (!strcasecmp(argv[++i],"ascii"))
        format = 0;
      else if (!strcasecmp(argv[i],"binary"))
        format = 1;
      else
        format = atoi(argv[i]);
    }
    else if (!strcmp(argv[i],"-nviz") && i < argc-1)
      n[0] = n[1] = n[2] = atoi(argv[++i]);
    else if (!strcmp(argv[i],"-1D"))
      dims = 1;
    else if (!strcmp(argv[i],"-2D"))
      dims = 2;
    else if (!strcmp(argv[i],"-last"))
      last = true;
    else if (!strcmp(argv[i],"-start") && i < argc-1)
      start = atoi(argv[++i]);
    else if (!strcmp(argv[i],"-starttime") && i < argc-1)
      starttime = atof(argv[++i]);
    else if (!strcmp(argv[i],"-end") && i < argc-1)
      end = atoi(argv[++i]);
    else if (!strcmp(argv[i],"-endtime") && i < argc-1)
      endtime = atof(argv[++i]);
    else if (!strcmp(argv[i],"-ndump") && i < argc-1)
      skip = atoi(argv[++i]);
    else if (!infile)
      infile = argv[i];
    else if (!vtffile)
      vtffile = argv[i];
    else
      std::cerr <<"  ** Unknown option ignored: "<< argv[i] << std::endl;

  if (!infile) {
    std::cout <<"usage: "<< argv[0]
              <<" <inputfile> [<vtffile>|<vtufile>] [-nviz <nviz>] \n"
              << "[-ndump <ndump>] [-last] [-start <level>] [-end <level>]\n"
              << "[-starttime <time>] [-endtime <time>] [-1D|-2D]\n"
              << "[-format <0|1|ASCII|BINARY>]\n";
    return 0;
  }
  else if (!vtffile)
    vtffile = infile;

  std::cout <<"\n >>> IFEM HDF5 to VT[F|U] converter <<<"
            <<"\n ==================================\n"
            <<"\nInput file: " << infile;

  std::cout <<"\nOutput file: "<< vtffile
            <<"\nNumber of visualization points: "
            << n[0] <<" "<< n[1] << " " << n[2] << std::endl;

  VTF* myVtf;
  if (strstr(vtffile,".vtf"))
    myVtf = new VTF(vtffile,format);
  else
    myVtf = new VTU(vtffile,last?1:0);

  // Process XML - establish fields and collapse bases
  PatchMap patches;

  HDF5Writer hdf(strtok(infile,"."),ProcessAdm(),true,true);
  XMLWriter xml(infile,ProcessAdm());
  xml.readInfo();

  int levels = xml.getLastTimeLevel();
  std::cout <<"Reading "<< infile <<": Time levels = "<< levels << std::endl;

  const std::vector<XMLWriter::Entry>& entry = xml.getEntries();
  std::vector<XMLWriter::Entry>::const_iterator it;

  ProcessList processlist;
  for (it = entry.begin(); it != entry.end(); ++it) {
    if (!it->basis.empty() && it->type != "restart") {
      processlist[it->basis].push_back(*it);
      std::cout << it->name <<"\t"<< it->description <<"\tnc="<< it->components
                <<"\t"<< it->basis << std::endl;
    }
    if (it->type == "eigenmodes") {
      levels = it->components-1;
      processlist[it->basis].back().components = 1;
    }
    if (it->type == "nodalforces")
      processlist["nodalforces"].push_back(*it);
  }

  if (processlist.empty()) {
    std::cout << "No fields to process, bailing" << std::endl;
    exit(1);
  }

  ProcessList::const_iterator pit = processlist.begin();

  double time = 0.0;

  // setup step boundaries and initial time
  if (starttime > 0)
    start = (int)(floor(starttime/pit->second.begin()->timestep));
  if (endtime > 0)
    end = int(endtime/pit->second.begin()->timestep+0.5f);
  if (end == -1)
    end = levels;
  time=last?end  *pit->second.begin()->timestep:
            start*pit->second.begin()->timestep;

  bool ok = true;
  int block = 0;
  VTFFieldBlocks fieldBlocks;
  int k = 1;
  for (int i = last?end:start; i <= end && ok; i += skip) {
    if (levels > 0) {
      if (processlist.begin()->second.begin()->timestep > 0) {
        hdf.readDouble(i,"timeinfo","SIMbase-1",time);
        std::cout <<"Time level "<< i;
        std::cout << " (t=" << time << ")";
      } else
        std::cout << "Step " << i+1;

      std::cout << std::endl;
    }
    VTFList vlist, slist;
    bool geomWritten=false;

    if ((isLR && hdf.hasGeometries(i)) || patches.empty()) {
      patches = setupPatchMap(processlist, hdf.hasGeometries(i)?i:0, hdf, dims, n, *myVtf, block, k);
      geomWritten = true;
    }

    for (pit = processlist.begin(); pit != processlist.end(); ++pit) {
      for (it = pit->second.begin(); it != pit->second.end() && ok; ++it) {
        if (it->once && k > 1)
          continue;
        if (pit->first != "nodalforces" && patches[pit->first].Patch.empty()) {
          if (k == 1)
            std::cerr << "Ignoring \"" << it->name << "\", basis not loaded" << std::endl;
          continue;
        }
        std::cout <<"Reading \""<< it->name <<"\""<< std::endl;
        if (pit->first == "nodalforces") {
          Vector vec;
          hdf.readVector(i, it->name, -1, vec);
          std::vector<Vec3Pair> pts(vec.size()/6);
          for (size_t j=0;j<vec.size()/6;++j) {
            for (int l=0;l<3;++l) {
              pts[j].first[l] = vec[6*j+l];
              pts[j].second[l] = vec[6*j+l+3];
            }
          }
          int geoBlck=-1;
          ok = myVtf->writeVectors(pts,geoBlck,++block,it->name.c_str(),k);
          continue;
        }
        for( int j=0;j<pit->second[0].patches;++j) {
          Vector vec;
          ok = hdf.readVector(it->once?0:i,it->name,j+1,vec);

          if (it->name.find('+') != std::string::npos) {
            /*
            Temporary hack to split a vector into scalar fields.
            The big assumption here is that the individual scalar names
            are separated by '+'-characters in the vector field name
            */
            Matrix tmp(it->components,vec.size()/it->components);
            tmp.fill(vec.ptr());
            size_t pos = 0;
            size_t fp = it->name.find('+');
            std::string prefix;
            if (fp != std::string::npos) {
              size_t fs = it->name.find(' ');
              if (fs < fp) {
                prefix = it->name.substr(0,fs+1);
                pos = fs+1;
              }
            }
            for (size_t r = 1; r <= tmp.rows() && pos < it->name.size(); r++) {
              size_t end = it->name.find('+',pos);

              ok &= writeFieldPatch(tmp.getRow(r),1, *patches[pit->first].Patch[j],
                                    patches[pit->first].FakeModel[j],
                                    patches[pit->first].StartPart+j,
                                    block, prefix+it->name.substr(pos,end-pos),
                                    vlist, slist, *myVtf, it->description, it->type);
              pos = end+1;
            }
          }
          else {
            if (it->type == "knotspan") {
              ok &= writeElmPatch(vec,*patches[pit->first].Patch[j],myVtf->getBlock(j+1),
                                  patches[pit->first].StartPart+j,block,
                                  it->description, it->name, slist, *myVtf);
            } else if (it->type == "eigenmodes") {
              ok &= writeFieldPatch(vec,it->components,
                                    *patches[pit->first].Patch[j],
                                    patches[pit->first].FakeModel[j],
                                    patches[pit->first].StartPart+j,
                                    block,it->name,vlist,slist,*myVtf, it->description, it->type);
            } else {
              ok &= writeFieldPatch(vec,it->components,
                                    *patches[pit->first].Patch[j],
                                    patches[pit->first].FakeModel[j],
                                    patches[pit->first].StartPart+j,
                                    block,it->name,vlist,slist,*myVtf, it->description, it->type);
            }
          }
        }
      }
    }
    if (geomWritten)
      myVtf->writeGeometryBlocks(k);
    writeFieldBlocks(vlist,slist,*myVtf,k,fieldBlocks);

    if (!ok)
      return 3;

    bool res;
    if (processlist.begin()->second.begin()->type == "eigenmodes") {
      double val;
      bool freq=false;
      if (!hdf.readDouble(i, "1", "eigenval", val)) {
        freq = true;
        hdf.readDouble(i, "1", "eigenfrequency", val);
      }
      res=myVtf->writeState(k++, freq?"Frequency %g" : "Eigenvalue %g", val, 1);
    } else if (processlist.begin()->second.begin()->timestep > 0)
      res=myVtf->writeState(k++,"Time %g",time,0);
    else {
      double foo = k;
      res=myVtf->writeState(k++,"Step %g", foo, 0);
    }
    if (!res) {
      std::cerr << "Error writing state" << std::endl;
      return 4;
    }

    pit = processlist.begin();
    time += pit->second.begin()->timestep*skip;
  }
  hdf.closeFile(levels,true);
  delete myVtf;

  return 0;
}
/**
 * Launch an application (webApps only, not native).
 *
 * @param appId The application ID to launch.
 * @param params The call parameters.
 * @param the ID of the application performing the launch (can be NULL).
 * @param launchingProcId (can be NULL).
 * @param errMsg The error message (will be empty if this call was successful).
 *
 * @todo: this should now be moved private and be protected...leaving it for now as to not break stuff and make things
 * slightly faster for intra-sysmgr mainloop launches
 *
 * @return The process ID of the newly launched application. Empty upon error. If empty lool at errMsg.
 */
std::string ProcessManager::launch(const std::string& appDescString, const std::string& params, 
		const std::string& launchingAppId, const std::string& launchingProcId, std::string& errMsg)
{
	std::string processId = "";
	ApplicationDescription* desc = ApplicationDescription::fromJsonString(appDescString.c_str());
	errMsg.erase();

	// This now will only launch Web Apps. Native Apps are now launched by the WebAppMgrProxy.

	// Find out what type of window we need to create
	Window::Type winType = Window::Type_Card;
	std::string winTypeStr;
	if (extractFromJson(params, "windowType", winTypeStr)) {

		if (winTypeStr == "dashboard")
			winType = Window::Type_Dashboard;
		else if (winTypeStr == "popupalert")
			winType = Window::Type_PopupAlert;
		else if (winTypeStr == "emergency")
			winType = Window::Type_Emergency;
		else if (winTypeStr == "dockModeWindow") // $$$ FIX THIS, it is just a patch to test Dock mode apps for now
			winType = Window::Type_DockModeWindow;
		else {
			winType = Window::Type_Emulated_Card;

			if (desc->uiRevision() == 2) {
				winType = Window::Type_Card;
			}
		}
	}
	
	if (winType == Window::Type_Card) {
		if (desc->uiRevision() != 2) {
			winType = Window::Type_Emulated_Card;
		}

	}
		
	// Get a list of all apps
	typedef std::list<const ProcessBase*> ProcessList;	
	ProcessList runningApps = WebAppManager::instance()->runningApps();
	const ProcessBase* app = 0;
	
	for (ProcessList::const_iterator it = runningApps.begin(); it != runningApps.end(); ++it) {
		if ((*it)->appId() == desc->id()) {
			app = (*it);
			processId = app->processId();
			break;
		}
	}
	
	if (!app) {

		// App not running? Launch it

		std::string url = desc->entryPoint();

		if (desc->isHeadLess())
			winType = Window::Type_None;

		processId = processIdFactory();

		WebAppManager::instance()->onLaunchUrl(url.c_str(),
											   winType,
											   appDescString.c_str(),
											   processId.c_str(),
											   params.c_str(), launchingAppId.c_str(), launchingProcId.c_str());
		g_debug("Launched Id %s", processId.c_str() );
	}
	else {
		WebAppManager::instance()->onRelaunchApp(processId.c_str(), params.c_str(), launchingAppId.c_str(), launchingProcId.c_str());
	}
	
	delete desc;
	
	return processId;
}
int main(int argc, char **argv) {
    cleanUpExitFlag = 0;
    resetOutputFileFlag = 0;

    ProcReducerConfig config(argc, argv);

	if (config.daemonize) {
		daemonize();
	}
    if (config.pidfile.length() > 0) {
        pidfile(config.pidfile);
    }

    ProcAMQPIO *conn = new ProcAMQPIO(config.mqServer, config.mqPort, config.mqVHost, config.mqUser, config.mqPassword, config.mqExchangeName, config.mqFrameSize, FILE_MODE_READ);
    conn->set_context(config.hostname, config.identifier, config.subidentifier);
    ProcHDF5IO* outputFile = NULL;

    time_t currTimestamp = time(NULL);
    time_t lastClean = 0;
    struct tm currTm;
    memset(&currTm, 0, sizeof(struct tm));
    currTm.tm_isdst = -1;
    localtime_r(&currTimestamp, &currTm);
    int last_hour = currTm.tm_hour;
    string hostname, identifier, subidentifier;

    int saveCnt = 0;
    int nRecords = 0;
    string outputFilename;
    int count = 0;
    void* data = NULL;
    size_t data_size = 0;

    char buffer[1024];
    unordered_map<std::string, ProcessList*> processLists;
    processLists.reserve(1000);
    ProcessList* spare_processList = new ProcessList(config.maxProcessAge);

    signal(SIGINT, sig_handler);
    signal(SIGTERM, sig_handler);
    signal(SIGXCPU, sig_handler);
    signal(SIGUSR1, sig_handler);
    signal(SIGUSR2, sig_handler);
    signal(SIGHUP, sighup_handler);

    while (cleanUpExitFlag == 0) {
        currTimestamp = time(NULL);
        localtime_r(&currTimestamp, &currTm);

        if (currTm.tm_hour !=  last_hour || outputFile == NULL || resetOutputFileFlag == 2) {
            /* flush the file buffers and clean up the old references to the old file */
            if (outputFile != NULL) {
                outputFile->flush();
                delete outputFile;
                outputFile = NULL;
            }

            /* dump the hash table - we need a fresh start for a fresh file */
            for (auto iter = processLists.begin(), end = processLists.end(); iter != end; ++iter) {
                ProcessList* list = iter->second;
                list->expire_all_processes();
            }

            /* use the current date and time as the suffix for this file */
            strftime(buffer, 1024, "%Y%m%d%H%M%S", &currTm);
            outputFilename = config.outputHDF5FilenamePrefix + "." + string(buffer) + ".h5";
            outputFile = new ProcHDF5IO(outputFilename, FILE_MODE_WRITE);
            resetOutputFileFlag = 0;
        }
        last_hour = currTm.tm_hour;

        ProcRecordType recordType = conn->read_stream_record(&data, &data_size, &nRecords);
        conn->get_frame_context(hostname, identifier, subidentifier);

        if (data == NULL) {
            continue;
        }
        ProcessList* currList = NULL;
        auto procList_iter = processLists.find(hostname);
        if (procList_iter == processLists.end()) {
            /* new host! */
            currList = new ProcessList(config.maxProcessAge);
            auto insertVal = processLists.insert({hostname, currList});
            if (insertVal.second) {
                procList_iter = insertVal.first;
            } else {
                cout << "couldn't insert new host processlist for: " << hostname << endl;
                delete currList;
                currList = NULL;
            }
        } else {
            currList = procList_iter->second;
        }

        outputFile->set_context(hostname, identifier, subidentifier);
        int last_pid = -1;
        ProcessRecord *last_record = NULL;
        for (int i = 0; i < nRecords; i++) {
            unsigned int recId = 0;
            bool saveNewRec = false;
            unsigned int recID = 0;
            ProcessRecord* record = NULL;

            int pid = get_record_pid(recordType, data, i);
            if (currList != NULL) {
                bool newRecord = false;
                record = currList->find_process_record(pid);
                if (record == NULL) {
                    record = currList->new_process_record(spare_processList);
                    newRecord = true;
                } 
                if (record == NULL) {
                    cout << "couldn't get a new record!" << endl;
                } else {
                    set_process_record(recordType, data, i, record, newRecord, outputFile);
                }
            }
        }

        time_t currTime = time(NULL);
        if (currTime - lastClean > config.cleanFreq || cleanUpExitFlag != 0 || resetOutputFileFlag == 1) {
            cout << "Begin Clean; Flushing data to disk..." << endl;
            outputFile->flush();
            outputFile->trim_segments(currTime - config.maxProcessAge);
            cout << "Flush Complete" << endl;

            int before_processes = 0;
            int before_process_capacity = 0;
            int after_processes = 0;
            int after_process_capacity = 0;
            for (auto iter = processLists.begin(), end = processLists.end(); iter != end; ++iter) {
                ProcessList *list = iter->second;
                before_processes += list->get_process_count();
                before_process_capacity += list->get_process_capacity();
                list->find_expired_processes(spare_processList);
                after_processes += list->get_process_count();
                after_process_capacity += list->get_process_capacity();
            }
            time_t nowTime = time(NULL);
            time_t deltaTime = nowTime - currTime;
            cout << "Cleaning finished in " << deltaTime << " seconds" << endl;
            cout << "End Clean: Presently tracking " << after_processes << " processes (removed " << (before_processes - after_processes) << ")" << endl;
            cout << "Capacity for " << after_process_capacity << " processes." << endl;
            cout << "Reserve capacity: " << spare_processList->get_process_capacity() << endl;
            lastClean = currTime;
            if (resetOutputFileFlag == 1) {
                resetOutputFileFlag++;
            }
        }
    }
    free(data);

    /* clean up all the records */
    for (auto iter = processLists.begin(), end = processLists.end(); iter != end; ) {
        ProcessList *record = iter->second;
        delete record;
        processLists.erase(iter++);
    }
    if (outputFile != NULL) {
        outputFile->flush();
        delete outputFile;
        outputFile = NULL;
    }
    if (conn != NULL) {
        delete conn;
        conn = NULL;
    }
    if (spare_processList != NULL) {
        delete spare_processList;
    }
    return 0;
}