Getting previous exit code of an application on Windows - windows

Is there any way to find out what was the last Exit Code of an application the last time it run?
I want to check if application wasn't exit with zero exit code last time (which means abnormal termination in my case) And if so, do some checking and maybe fix/clean up previously generated data.
Since some applications do this (they give a warning and ask if you want to run in Safe Mode this time) I think maybe Windows can tell me this.
And if not, what is the best practice of doing this? Setting a flag on a file or something when application terminated correctly and check that next time it executed?

No, there's no permanent record of the exit code. It exists only as long as a handle to the process is kept open. And returned by GetExitCodeProcess(), it needs that handle. As soon as the last handle is closed then that exit code is gone for good. One technique is a little bootstrapper app that starts the process and keeps the handle. It can then also do other handy things like send alerts, keep a log, clean up partial files or record minidumps of crashes. Use WaitForSingleObject() to detect the process exit.
Btw, you definitely want to exit code number to mean the opposite thing. A zero is always the "normal exit" value. This helps you detect hard crashes. The exit code is always non-zero when Windows terminates the app forcibly, set to the exception code.
There are other ways, you can indeed create a file or registry key that indicates the process is running and check for that when it starts back up. The only real complication with it is that you need to do something meaningful when the user starts the program twice. Which is a hard problem to solve, such apps are usually single-instance apps. You use a named mutex to detect that an instance of the program is already running. Imprinting the evidence with the process ID and start time is workable.

There is no standard way to do this on the Windows Platform.
The easiest way to handle this case is to put a value on the registry and to clear it when the program exits.
If the value is still present when the program starts, then it terminated unexpectedly.
Put a value in the HKCU/Software// to be sure you have sufficient rights (the value will be per user in this case).

Related

Waiting for closing of previously started program

I would like to ask you how to specify waiting for closing of specific program which was started before. I am showing here an example with command waitfor but unfortunately I don't know how to write it correctly, therefore I am asking you for help.
system('"C:\Program Files\Google\Chrome\Application\chrome.exe" &');
waitfor "closing of chrome.exe"
You should follow the advice in this other Q&A to find the PID of the new program right after you start it. Then, in a loop, check to see if that PID is still running (using again the same process as before), and pause(1) to avoid checking too frequently.
I guess you can do something like:
time_in_seconds=60
while ~isfile("output_folder/file.db")
pause(time_in_seconds)
end
Note that this program, as is, requires that file to exist at some point, otherwise infinite loop. Make sure you put safeguards to end it in case the file does not get created (like a time limit).
But I am not sure it makes sense to have MATLAB waiting for 40 minutes for a script to finish...

Trap flag, debuggers and misc

This is my first question in Stack Overflow, since up until now, I always managed to find my answers.
So.. I'm writing a debbuger (for Windows, in python, using WinAppDbg library) that should trace the program execution, and encountered some problems.
I'm setting the trap flag, so I could stop every single step.
First problem - sometimes the execution flow goes through a Windows api, which goes to the kernel. When it returns, obviously the trap flag is off, and the execution of the thread may continue millions of instructions without my debbuger tracing every step of it.
Chance of solution - before a Windows api is called, I set the next addresses permissions as guard page, thus when the call returns, I get a guard page exception, setting the trap flag again, and continue tracing. But this cause a different problem (I call it "second problem")
Second problem - since I'm setting the trap flag of my main thread, all I see is a loop of that thread (I guess it's the Windows gui loop), and the program execution isn't advancing (for example, there should be new threads created, but I don't see them).
So what am I looking for?
A debugger's source code that can handle the problems I've described.
Or better yet, a solution to my problems. What am I doing wrong?
Thank you all!

Windows 7 task scheduler keeps returning operational code 2

I set up a scheduled task to run under my account. Everything it runs, even if it is successful, returns an operational code of (2). I looked this up this error code at the below link, and it claims it cannot find the specific file.
http://www.hiteksoftware.com/knowledge/articles/049.htm
Even if I do something very simple, I get back operational code of (2). For example:
run program: cmd.exe
start in path: c:\windows\system32
I start the task and I see the process running in my task manager, so I kill the task. I then check in the history of scheduled task and it shows up as (2).
Something more realistic of what I am doing:
<?
/* file in c:\php\test.php */
echo "hello";
?>
run program: php.exe
start in path: c:\php
arguments: -f test.php
Everything works in the command line, but Windows schedule task keeps returning operational code (2). I should be seeing an operational code of (0), which means successful, correct?
You may not have put a path in the "Start In (Optional) box of the Edit Action dialog box.
Even though you had a path on the program that was being executed, Windows 7 still wants you to tell it where to run the program.
TL/DR: Don't worry about it. This just means the task finished, but tells you nothing about whether it was successful or how it failed. Look at the "Last Run Result" for that information.
The question and the top answer are confusing the notion of a "return code", which shows up in Task Scheduler as the "Last Run Result" with the "OpCode"/"Operational Code" that shows up in the history of a task.
If I create a simple Python program that does nothing more than sys.exit(7), and run it via task scheduler, I get a Last Run Result of 0x7, and an opcode of 2. If I have it do nothing, or sys.exit(0), I get a Last Run Result of "The operation completed successfully (0x0)" and still an opcode of 2. In other words, the return code from the executed program determines the Last Run Result. The OpCode appears to be a constant 2. This also establishes that the opcode 2 is not related to the return code 2 that likely means the file's not found. We know the file was found as it executed, and returned different Last Run Results depending on the code contained.
Further, a Windows forum post points out that this history view is really coming out of the event log. Sure enough, I can find the same events in the event log (always with a value of 2). This means the definition of the OpCode is going to be the same as the definition used for events, and is less of a task scheduler concept than a Windows event concept.
What is an opcode for an event? I've struggled to get a clear answer, but as best I can tell, it appears it's ultimately controlled by the program writing to the event log. There's documentation around for defining opcodes in your program. In this case, the thing writing to the event log would be Task Scheduler itself or something else in Windows.
A final observation: If I go to the event viewer and look for Log: Microsoft-Windows-TaskScheduler/Operational, Source: Microsoft-Windows-TaskScheduler and Event ID: 102,201, add the column for Operational Code, and sort, I see it is always a 2. And events 100 and 200 are always a 1. This applies not just to my manual experiments, but also includes every other random program that's using scheduled tasks, e.g. Dropbox and Google updaters that are working as far as I know.
Put all this together and I would strongly bet that the events generated while starting up a scheduled task are hardcoded by Windows to use an opcode of 1 when writing to the event log, and the events generated while finishing a task (successful or not - which goes in the Last Run Result) are hardcoded by Windows to use an opcode of 2 when writing to the event log. This opcode appears to be a red herring that doesn't affect anything we need to worry about beyond curiosity.
I was striking out until I just deleted & re-created the scheduled task...now it works. Don't know why but there it is.
Okay I know I am late to the party here, but I think a lot of the problem stems from confusing the Operational Code with a Return Code. I'm not an expert in Windows programming or internals (I make a living using a Windows system to program, but my programming isn't for Windows systems).
If I understand correctly:
The Operational Code is set by what ever routine being run at whatever value the programmer decided to set it at.
The Return Code is indicative of success or failure.
Consider the following (edited) example from the history of one of my scheduled tasks:
Event 201, Task Category "Action completed" shows an Operational Code of (2).
Down below under the General tab, is the message:
Task Scheduler successfully completed task "\My_task" , instance "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" , action "C:.....\blahblah.exe" with return code 0.
There's the indication of success. A different return code would indicate a failure. The Operational Code of (2) merely indicates that the routine was finished (in this case) when reported. I don't believe there's any set values to be interpreted for the Operation Code.
I've been having a similar issue and found that in addition to what was suggested in both the accepted answer and its comments I had to do one other thing. I had to re-create the task and set its "configure for" to Windows Server 2003, Windows XP, or Windows 2000 I dont understand why, since its not for any of those OS' but after I did so my task actually worked.
If this runs, and works, yet you still get an error code try entering exit 0 at the end of your script.
It took me a lot of googling to find that so hopefully this is helpful to someone.
#ojchase is right.
Opcodes are attached to events by the event provider. An opcode defines a numeric value that identifies the activity or a point within an activity that the application was performing when it raised the event.
Opcode 1 means that, when producing the event, the application was in the start of an activity.
Opcode 2 means that, when producing the event, the app. was at the end of an activity.
So opcodes have little to do with success or failure.
Sources:
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.standardeventopcode?view=net-5.0
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventopcode?view=net-5.0

Get current state of caps/scroll/numlock in windows w/o using Peek/ReadConsoleInput()

I'm programming a Windows console application in plain C and using PeekConsoleInput/ReadConsoleInput to get keystrokes from the user and process them.
I need to get the current state of the Caps Lock, Scroll Lock, and Num Lock keys when the program starts, before the user has entered anything. Meaning there would be no KEY_EVENTs in the message queue to process.
Is this possible to do? If so, how? I've looked at most of the functions in wincon.h and nothing seems appropriate.
You can call GetAsyncKeyState three times, and it will usually work, but there are a few cases where it still won't work for you. The arguments for your three calls would be VK_CAPITAL, VK_SCROLL, and VK_NUMLOCK.

Checking whether ruby script is running in windows

I need to run a ruby script for one week and check whether it is running for every hour.
Could you please suggest me some way? I need to check this in windows machine.
For ex:- I have script called one_week_script.rb which will run for one week, in between i want to check whether the script is running or not? if it is not running, then running that script from another script
A typical solution is to use a "heartbeat" strategy. The "to be monitored" notifies a "watchdog" process on a regular interval. A simple way of doing this might be to update the contents of some file every so often, and the watchdog simply checks that same file to see if it's got recent data.
The alternative, simply checking if the process is still 'loaded' has some weaknesses, The program could be locked up, even though it's still apparently 'running'. Using the heartbeat/watchdog style means you know that the watched process is operating normally, because you're getting feedback from it.
In a typical scenario, you might just write the current time, and some arbitrary diagnostic data, say the number of bytes processed (whatever that might mean for you).

Resources