Process Manager - c++

I'm trying to make a kernel simulation as my DSA (data structure and algorithm) project in C++. There will be different modules(process manager, memory manager etc.) in it. Right now i have to make a Process Manager and I've only a little a idea about it (like, i can use a queue). Can anyone help me how can i make a process manager in c++.

First make a scheduler (unless you understand "process manager" as what is commonly known as a "scheduler".) you must decide upon multitasking model, cooperative vs preemptive. Preemptive may be difficult - use some kind of interrupts and so on... may be unnecessarily complex for a school project.
If you don't know which model to pick, I strongly suggest cooperative multitasking. It is where each process takes a certain small slice of time, then returns control to the scheduler by itself - say, after going through one iteration of its "main loop". Usually done by the main loop calling some kind of "task()" function of the process-class, and the task() ending with a 'return', with no long loops underway.
Start with a model of a "task/process". Should it be loadable (say, as a shared object file), or predefined at startup (a class). Entry point, persistent state storage, "main loop" routine with a finite state machine (usually implemented as a switch that moves between various states). The task works by repeatedly launching the "entry point" routine.
The states to be implemented will likely be:
init, launched on startup, once
idle - check for requests for activity, if none, return control
various "work" states.
Once you have that, prepare a dynamic queue of such tasks. Adding, removing, iterating, elevated priority = call out of order, and so on. The "scheduler" iterates through all the tasks and starts the "startup routine" of each of them.
When you have that ready, you can write what is commonly known as "task manager" - a program that edits the list. Remove a program from the queue, add a new one, change priority, pause etc.
To help you imagine, you currently usually write:
int main()
{
do_something1();
do_something2();
}
void do_something1()
{
//initialize
...perform stuff
int x=0;
//main loop
do {
if(condition...) {
...perform stuff
} else {
...perform other stuff
blargh(x);
x++;
}
} while(!end);
//ending
//finish...
...mop up.
}
What you need to write:
int main()
{
//main loop
do {
do_something1();
do_something2();
} while(!global_end);
}
void do_something1()
{
static state_enum state = STATE_INI;
static int x=0;
switch(state)
{
case STATE_INI:
//initialize
...perform stuff
state = STATE_WORK1;
x=0;
break;
case STATE_WORK1:
//main loop, mode 1
...perform stuff
if(condition) state = STATE_WORK2;
if(condition2) state = STATE_END;
if(condition4) state = STATE_IDLE;
break;
case STATE_WORK2:
//main loop, mode 2
...perform stuff
blargh(x);
x++;
if(condition3) state = STATE_WORK1;
if(condition4) state = STATE_IDLE;
break;
case STATE_IDLE:
//do nothing
//don't do any stuff.
if(any_condition) state = STATE_WORK1;
break;
case STATE_END:
//finish...
...mop up.
break;
}
return;
}
...and your process manager will be replacing what constitutes static calls to
do_something1();
do_something2();
with a dynamic list of functions to call.
fyi, writing apps for preemptive scheduling system is much easier, you just write them like in the first version, never worrying about preserving state between calls (static), or returning control, or keeping each case statement short and sweet with very short, if any loops inside, unrolling bigger ones. But writing the scheduler itself, interrupting a program and saving its state, then restoring it and resuming from where it interrupted is much, much harder.

A process manager manages processes. Obviously, to refine that, you first need to define what constitutes a process in your OS. There's no reason for a process manager to deal with threads when all your processes are single-threaded, for instance. And if you don't have virtual memory, that doesn't need to be managed either.
You did note that you'd have a memory manager. This is certainly possible outside the process manager, but you would need to define the interface between them. For instance, the process manager would need to allocate memory to load the program code on startup; the program itself cannot do that (chicken and egg problem).

Related

In AnyLogic, how do I return a crane to automatic mode (idle state) after executing a CraneProgram?

AnyLogic (version 8.7.5) OverheadCrane is working well in automatic mode.
I use the moveByCrane logic blocks to move other agents from one location to another.
But I'd like to modify the behaviour just a little. After the crane has finished its move, I'd like it to lift the hook up out of the way.
There is a facility for operating cranes manually: the CraneProgram. In the crane's "On bridge state change" action, I use the following code to lift the hook up.
traceln("crane.onStateChange() "+newState);
if (newState == OverheadCraneBridgeState.IDLE) {
traceln(" Raising hook");
CraneProgram cp = new CraneProgram();
cp.moveHook(8, METER);
bridge.moveByProgram(cp);
}
This works nicely, except that the crane proceeds through MOVING_UNLOADED state and ends up in the WAITING state, and in that state it will not automatically work on any agents that are subsequently available to be moved.
The documentation describes WAITING as:
The bridge is seized by the agent, but this agent is currently moving through any blocks that are not SeizeCrane, MoveByCrane, or ReleaseCrane blocks. Also includes cases where the bridge in manual mode remains at target, executes a programmed delay command, or has finished the program and waits for the next command.
Is there a way to tell the crane that there will be no "next command", and it should switch from manual mode back to automatic mode?
Advice from AnyLogic support, received with thanks:
In this case I advise you to use “moveTo(…)” function of a bridge instead of using “CraneProgram” class. This function has “remainsAsTarget” argument, that allows you to use the required behavior when it reaches the destination.
Essence of solution:
if (newState == OverheadCraneBridgeState.IDLE && !movedHookUp) {
Point newPosition = new Point(endNode.getX(),endNode.getY(),endNode.getZ()+toPixels(8, LengthUnits.METER))
bridge.moveTo(newPoint, //destination
8, // safety height
false); // remainsAtTarget - see documentation
movedHookUp = true;
}
See moveTo function in the bridge documentation.

periodic state machine with boost statechart

I want to implement a state machine that will periodically monitor some status data (the status of my system) and react to it.
This seems to be something quite basic for a state machine (I've had this problem many times before), but I could not find a good way to do it. Here is some pseudo code to explain what I'd like to achieve:
// some data that is updated from IOs for example
MyData data;
int state = 0;
while( true ) {
update( & data ); //read a packet from serial port
//and update the data structure
switch( state ) {
case 0:
if( data.field1==0 ) state = 1;
else doSomething();
break;
case 1:
if( data.field2>0 ) state = 2;
else doSomethingElse();
break;
// etc.
}
usleep(100000); //100ms
}
Of course on top of that, I want to be able to execute some actions upon entering and exiting a state, maybe do some actions at each iteration of the state, have substates, history, etc. Which is why this simplistic approach quickly becomes impractical, hence boost statechart.
I've thought about some solutions, and I'd like to get some feedback.
1) I could list all my conditions for transitions and create an event for each one. Then I would have a loop that would monitor when each of those boolean toggles. e.g. for my first condition it could be:
if( old_data.field1!=0 && new_data.field1==0 )
// post an event of type Event 1
but it seems that it would quickly become difficult
2) have a single event that all states react to. this event is posted whenever some new status data is available. As a result, the current state will examine the data and decide whether to initiate a transition to another state or not
3) have all states inherit from an interface that defines a do_work(const MyData & data) method that would be called externally in a loop, examine the data and decide whether to initiate a transition to another state or not
Also, I am opened to using another framework (i.e. Macho or boost MSM)
Having worked with boost MSM, statecharts and QP my opinion is that you are on the right track with statecharts. MSM is faster but if you don't have much experience with state machines or meta programming the error messages from MSM are hard to understand if you do something wrong. boost.statecharts is the cleanest and easiest to understand. As for QP its written in embedded style (lots of preprocessor stuff, weaker static checking) although it also works in a PC environment. I also believe its slower. It does have the advantage of working on a lot of small ARM and similar processors. Its not free for commercial use as opposed to boost solutions.
Making an event for every type of state change does not scale. I would make one type of event EvStateChanged give it a data member containing a copy or reference to the dataset (and maybe one to the old data if you need it). You can then use costume reactions to handle whatever you need from any state context. Although default transitions work quite well in a toaster oven context (which are often used to demonstrate SM functionality) most real world SMs I have seen have many custom reactions, don't be shy to use them.
I don't really understand enough about your problem to give a code example but something along the lines of:
while( true ) {
update( & data ); //read a packet from serial port
//and update the data structure
if(data != oldData){
sm.process_event(EvDataChanged(data,oldData));
}
else{
timeout++;
if(timeout>MAX_TIMEOUT)
sm.process_event(EvTimeout());
}
usleep(100000); //100ms
}
and then handle your data changes in custome reactions depending on state along these lines:
SomeState::~SomeState(){
DoSomethingWhenLeaving();
}
sc::result SomeState::react( const EvDataChanged & e){
if(e.oldData.Field1 != e.newData.Field1){
DoSomething();
return transit<OtherState>();
}
if(e.oldData.Field2 != e.newData.Field2){
return transit<ErrorState>(); //is not allowed to change in this state
}
if(e.oldData.Field3 == 4){
return forward_event(); //superstate should handle this
}
return discard_event(); //don't care about anything else in this context
}

How to find whether a given application is single instance or not?

I am looking for an efficient way to find whether a given application (say app.exe) is single instance or not? I thought of these following sols:
Do CreateProcess() twice and check whether there are two or more instance running of that application? If no, it is single instance application. But, this is not efficient.
Do CreateProcess() and wait for 1-2 sec. If this instance is killed (because there is already an instance running for it), it will be single instance app.
But I am not convinced with both above sol. Is there any other efficient way of doing that in windows?
Please note that I don't to kill or make any modifications to an already running (if any) instance of that application.
Think about it the other way: When you write a program, how do you specify whether it is single-instance or multiple-instance? Is there a way that some other program can get that information out of your program without running it? (Once you answer this question, then you have the answer to your question.)
This problem is not solvable in general because single-instance/multiple-instance-ness is determined at runtime and can be based on runtime conditions. For example, some applications are "sometimes multiple instance, sometimes single": If you run the application to open document X, and then document Y, you will get two instances. But if you open document X, and then document X again, the two instances will fold into one. Other applications may have a configuration switch that lets you select whether they are single-instance or multiple-instance. Or maybe they decide to flip a coin and decide to be single-instance if tails and multiple-instance if heads.
The best way is via using synchronization object called Mutex (Mutually exclusive). You may google it.
I think the following code may help to.
//---------------------------------------------------------------------------
WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
try
{
HANDLE hMutex=OpenMutex(MUTEX_ALL_ACCESS,0,"SIns");
if (!hMutex) {
//Mutex doesn’t exist. This is the first instance so create the mutex.
//in this case app name is SIns (Single Instance)
hMutex=CreateMutex(0,0,"SIns");
Application->Initialize();
Application->MainFormOnTaskBar = true;
Application->CreateForm(__classid(TfMain), &fMain);
Application->Run();
ReleaseMutex(hMutex);
}
else{
//This is not single. The prev instance is already running
//so informing about it
//remember that if it finds prev instance we're activating it here
//you may do whatsoever here ...... e.g. you may kill process or stuff like this:)
ShowMessage("The program is already running. Switching to ...");
HWND hWnd=FindWindow(0,"SIns");
SetForegroundWindow(hWnd);
}
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
There is no way to do this at all. What happens if the application checks a mutex then makes a messagebox to tell the user an instance is already running and only when the user dismisses it does it kill the application? There are many different ways to ensure mutual exclusion via some shared resource, mutex, shared file, even maybe setting some registry key, the methods are unlimited.
The usual solution is to use some sort of a locking file. Under
traditional Unix, for example, the application will start by creating a
file (which will succeed even if the file exists), then try to create a
link to it (an atomic action); if that fails, the application will
immediately kill itself. Under Windows, the share mode of CreateFile
can be used to the same effect: open a file with share mode 0, and if
that fails, quit. (The Unix solution will leave the lock if the process
crashes, requiring it to be cleaned up manually. The Windows solution
will remove the lock if the system crashes.)
you may use mutexes... I do such check with following code:
bool insureApplicationUniqueness(HANDLE& mutexHandle)
{
mutexHandle=CreateMutexW(NULL,true,UNIQUE_INSTANCE_MUTEX_NAME);
if( mutexHandle&&(ERROR_ALREADY_EXISTS==GetLastError()))
{
CloseHandle(mutexHandle);
return false;
}
return true;
}
but this is for application which source code is yours and which checks is another instance of itself running.
The problem with the notion is that in common environments, there is no explicit static data that determines whether an application is single-instance. You only have behavior to go on, but you cannot fully test behavior.
What if you have an app that is multi-instance, but will fail to open a file that's already open? If you test it twice with the same, valid filename, it would create only a single process, but any other command line argument would cause two processes to exist. Is this a single-instance program?
You could even argue that "single instance" isn't a well-defined catageory of programs for this reason.

Basic design of a multithreaded game server?

How are multithreaded game servers written?
If there are 4 threads, is there one thread running the game loop, and 3 accepting and processing requests? Also: is information sent from the thread running the game loop?
Starkey already pointed out that it depends a whole lot on the precise design.
For instance, on games with many clients, you'd assign dedicated threads to handling input, but for games with a few clients (say <=16) there's no need for multiple threads.
Some games feature NPC's with considerable smarts. It may be smart to run those on their own threads, but if you have too many you'll need a threadpool so a bunch of NPC's can share a single thread.
If you've got a persistent world, you'll need to write out state to a hard disk somewhere (probably via a DB). Since that has serious latencies, you won't want to have a main game loop wait on that I/O. That will be another thread, then.
Finally, there's the question whether you even have a main game loop. Would a MMO have a single loop, or would you rather have many ?
The main key is to make sure your game logic is not affected by your threading model.
As such, most game servers look something like this:
main() {
gGlobalReadOnlyStuff = LoadReadOnlyStuff();
SpawnThreads(numCores); // could be another limiting resource...
WaitForThreadsToBeReadyToGo();
while(1) {
WaitForNetworkInput(networkInput);
switch(networkInput.msg) {
case ADMIN_THING: // start/stop websever, dump logs, whatever...
DoAdminThing(networkInput.params);
break;
case SPAWN_GAME: // replace 'game' with 'zone' or 'instance' as needed
idThread = ChooseBestThread(); // round robin, random, etc
PostStartGameMessageToThread(idThread, networkInput.msg);
break;
// ...
}
}
}
void ThreadUpdate() {
threadLocalStuff = LoadThreadLocalStuff();
SignalThreadIsReadyToGo();
while(1) {
lock(myThreadsMessageQueue);
// copy messages to keep lock short
localMessageQueue = threadsMessageQueue;
unlock(myThreadsMessageQueue);
foreach(message in localMessageQueue) {
switch(message.msg) {
case SPAWN_GAME:
threadLocalStuff.games.MakeNewGame(message.params));
break;
case ADMIN_THING__LET_EVERYONE_KNOW_ABOUT_SERVER_RESET:
...;
break;
// etc...
}
}
foreach(game in threadLocalStuff.games) {
game.Update(); // game will handle its own network communication
}
}
The two hard things then are 'coming up with a partition (game, zone, instance, whatever) appropriate for you game' and 'transitioning things (players, fireballs, epic lootz) across those boundaries' One typical answer is "serialize it through a database", but you could use sockets/messages/files/whatever. But yeah, where and how to make these partitions and minimizing what can go across the boundaries is intimately tied to your game design.
(And yes, depending on your setup, there are possibly a few 'shared' systems (logging, memory) that may need a multithreading treatment(or even better, just have one logger/heap per thread))

Handling Interrupt in C++

I am writing a framework for an embedded device which has the ability to run multiple applications. When switching between apps how can I ensure that the state of my current application is cleaned up correctly? For example, say I am running through an intensive loop in one application and a request is made to run a second app while that loop has not yet finished. I cannot delete the object containing the loop until the loop has finished, yet I am unsure how to ensure the looping object is in a state ready to be deleted. Do I need some kind of polling mechanism or event callback which notifies me when it has completed?
Thanks.
Usually if you need to do this type of thing you'll have an OS/RTOS that can handle the multiple tasks (even if the OS is a simple homebrew type thing).
If you don't already have an RTOS, you may want to look into one (there are hundreds available) or look into incorporating something simple like protothreads: http://www.sics.se/~adam/pt/
So you have two threads: one running the kernel and one running the app? You will need to make a function in your kernel say ReadyToYield() that the application can call when it's happy for you to close it down. ReadyToYield() would flag the kernel thread to give it the good news and then sit and wait until the kernel thread decides what to do. It might look something like this:
volatile bool appWaitingOnKernel = false;
volatile bool continueWaitingForKernel;
On the app thread call:
void ReadyToYield(void)
{
continueWaitingForKernel = true;
appWaitingOnKernel = true;
while(continueWaitingForKernel == true);
}
On the kernel thread call:
void CheckForWaitingApp(void)
{
if(appWaitingOnKernel == true)
{
appWaitingOnKernel = false;
if(needToDeleteApp)
DeleteApp();
else
continueWaitingForKernel = false;
}
}
Obviously, the actual implementation here depends on the underlying O/S but this is the gist.
John.
(1) You need to write thread-safe code. This is not specific to embedded systems.
(2) You need to save state away when you do a context switch.