How to simulate windows service crush - windows

I have very basic question, How to simulate windows service crush,
I found a way how to set the rules of a service to restart himself in case of failure,
Now I just want to check it,
I don't want to add code to my projects (I have 3) to simulate the crush, I prefer to simulate it from external,
I prefer so generic solution.
Thanks.

Possibilities:
manually locate the .exe of the service in Task Manager and terminate it
programmatically locate the service process and use the WINAPI TerminateProcess()

Related

Go program as windows service

how do i make my Go program supervised by some kind of systemd in linux, the requirement are :
restart on crash
start on boot
and my Go Program also has Administrator access (via manifest file), so is there any way to do that ?
For your first question, you could consider using a library like https://github.com/kardianos/service

debug a service windowns through your source code DELPHI? [duplicate]

Is there a way to debug completely a windows service with Delphi?
It's actually quite easy. Just use the standard DEBUG compiler directive to start the service as a console application instead of a service.
program MyServiceApp;
{$ifdef DEBUG}
{$APPTYPE CONSOLE}
{$endif}
uses
System.SysUtils,
[..]
begin
{$ifdef DEBUG}
try
// In debug mode the server acts as a console application.
WriteLn('MyServiceApp DEBUG mode. Press enter to exit.');
// Create the TService descendant manually.
ServerContainer1 := TServerContainer.Create(nil);
// Simulate service start.
ServerContainer1.ServiceStart(ServerContainer1, MyDummyBoolean);
// Keep the console box running (ServerContainer1 code runs in the background)
ReadLn;
// On exit, destroy the service object.
FreeAndNil(ServerContainer1);
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
WriteLn('Press enter to exit.');
ReadLn;
end;
end;
{$else}
// Run as a true windows service (release).
if not Application.DelayInitialize or Application.Installing then
Application.Initialize;
Application.CreateForm(TServerContainer, ServerContainer1);
Application.Run;
{$endif}
end.
You can use unitDebugService.pas from Colin Wilson's NT Low Level Utilities (page is gone, available in the wayback machine)
and then in the DPR:
begin
if (paramCount > 0) and (SameText(ParamStr(1), '-DEBUG')) then
begin
FreeAndNil (Application);
Application := TDebugServiceApplication.Create(nil);
end;
//... the rest of the normal DPR code
end.
This way you can run from within Delphi with debugging (by setting the project Debugger Parameters), use the EXE as a service, or run from the commandline with the -DEBUG switch, and .
Use Run -> Attach to process. This way you can debug a service without doing any changes to its code. The only tricky part maybe debugging the service start code, because attaching may require some time, and the start must happen in 30s (although you can tweak Windows to allow a longer time). You can use a delay (sleep...) to allow you to attach in time, or if you just need to see what happens you can use OutputDebugString() to print to the debug output (use Delphi Event View to see it).
Yes, there is:
Debugging services: an easy way
Do you create services with Delphi?
Then maybe you are also annoyed at the
time consuming way of starting,
restarting, killing and attaching to
the service process application every
time. Well, there is remedy.
You don’t need to do this. Instead run
Delphi as a SYSTEM application and do
some minor adaptions to the service
code.
I've tried this, but only appears the cpu window with assembly codes.
Then you only should solve this problem.
Basically, to debug a Win2 service, there are few ways:
Use "Attach to process" command to attach debugger to already running service. You may insert startup delays to have time to attach debugger, if you need to attach at the very beginning. However, you would also have to tweak the system to increase service timeouts.
Use "Image File Execution Options" registry key to force-run Delphi's debugger at service startup. The same considerations about system timeouts apply.
Temporary convert service into usual application and run it under debugger normally. You may re-launch IDE under different user account to gain more priviledges for the "service".
If you for some reason has only CPU view of your service after starting debugging - this means that Delphi's debugger can't find debug information for your service. That is a different problem and you should search solution for it.
Usually, you need to do:
Make sure that output folder for your service application is set to folder from which it will be loaded by the system. I.e. if your service is located in C:\Windows\System32 - then set output folder to C:\Windows\System32. Do not copy .exe file elsewhere from your output folder. For 64 systems you may try alias (sysnative/SysWOW64) or real name. I think it's best to set output path to project's folder and re-register service to be loaded from project folder.
(Optional) Set output path for DCU into the same folder as .exe file.
Delete all of your DCU files.
Make sure to enable debug options on "Compiler" page in project options.
(Optional) Additionally you may also include TD32/RSM/MAP options on "Linker" page.
Make sure there is no IDE expert/extension, which may modify .exe file, debug information or file modification date for these files.
Make sure there is no old files (DCU/exe) in other locations.
Make a full rebuild (Project/Build all).
Run your service.
Yes there is.
In your dpr:
Application.CreateForm(TMyService, MyService);
_ServiceInDebugMode := SysUtils.FindCmdLineSwitch('DEBUG', True);
if _ServiceInDebugMode then
DebugService(MyService)
else
SvcMgr.Application.Run;
DebugService is a procedure that creates a debug form, a service control thread and kicks off everything by calling Forms.Application.Run.
You can compare the service control thread with the Windows' SCM (Service Control Manager), the debug form with an application that talks to the SCM (such as the services.msc) to start and stop services. The service should also have its own thread (service thread) to respond to control codes coming in from the SCM or our service control thread and one or many more separate threads to do its actual work. You want separate threads for the actual work (instead of coding it in the event handlers of your TService descendant) to ensure that the thread in which the TService itself runs is always free to respond to control codes from the SCM and you can still stop and start the service even when per chance a/the worker thread is frozen.
This approach allows you to debug the service app code as well, but involves a fair amount of code and placing a couple of hooks into windows api functions to work properly. Too much to show here at short notice. Maybe I'll write it up in an article some day.
In the mean time, if you don't want to code it all yourself you have two options. Either go with a library such as SVCOM or the one mentioned by Mick which do it all for you, or when in debug mode by-pass the service code all together and "simply" start your service as a "normal" forms application. You will have to disentangle the real functionality of your service from your TService descendant's code/event handlers, but that is something I'd recommend anyway for the reasons mentioned above.

Window7 : run task at boot time and wait for it's completion

How do i run task at boot time and wait for it's completion? I know chkdsk and some other programs are doing that, but how?
Update: i found a way. Native API, if anyone's curious.
Windows have a "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute" key, programs in it are executed before any subsystem is started, i.e. before win32,LSA, etc. The only API avaliable at that time is NativeAPI. Most of it's functions can compromise security and stability of the system (This API can close handles, hide registry keys and more). Of course, a lot of it's functions are undocumented, but guys at http://undocumented.ntinternals.net/ have documented a lot of them.
Here is another method (not sure if this "Native API" is the same but you can use the Windows Task Schedular. There is a On Computer Start on or a User Login option too.
How to install/wrapper (Just for more info): Windows Task Scheduler Installer

Why when running a program through a service, is the program not actually shown?

When running a program, such as notepad, as a service do you not see the program visually?
I see notepad running in the task manager but I can't actually see its instance running. Why is this?
Services are meant as background applications, not foreground applications. Generally they run without direct user input or with user input through IPC (often providing a centralized point for multiple applications to communicate).
It's not common to setup any applications to just run as a service. Applications that run as a service are generally specifically engineered to do so because they perform certain tasks and may want to always be running to perform such tasks.
An application actually needs to support running as a service - typically it is done by recognizing the "\service" command line key. Some applications will recognize the absence of the "\service" key and either do nothing or show a warning.
When an application is started "as a service" it usually means that it has to work continuously in background and there's a chance that no user is currently logged on. That's why it should not expect any user input and therefore doesn't show the window.
Adding on #Quintin Robinson's answer, the reason why they doesn't show up on task manager is because they are (usually) run from an umbrella process.
To give you a better picture, download and run Microsoft's Process Explorer, then hold your mouse over one of the "svchost.exe" process running.
You should see some of the services that are running under it.
All user interaction in Windows takes place via Windowstations. By default, Windows services "interact" with a non-interactive station. It's not the station you're connected to, so you don't see any output.
You can change this behavior by changing the service properties, and enabling "Allow service to interact with desktop".
You can read more about this here.
Applications that run as a service (or that are launched by other applications that run as a service) by default run on a separate desktop that cannot interact with the desktop you see.
If you want to be able to interact with a service, you have set the service properties accordingly.
That being said, what you're seeing with Notepad almost certainly has nothing to do with services.

Sending the message Ctrl+Alt+Del from my application

I want to write a small utility in MFC which sends the Ctrl+Alt+Del message to OS. Can any one help me how do I achieve this? I tried:
::PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG( MOD_CONTROL | MOD_ALT, VK_DELETE));
But this is not working.
I want to send Ctrl+Alt+Del not to invoke TaskMgr.exe. Also, it is for my local OS (Windows XP Service pack 2). Basically I want to use this application to lock my machine and schedule some actions along with locking.
This is not a keystroke you can simulate. It's called the "Secure Attention Sequence".
Here's how to invoke it FROM A REMOTE DESKTOP (XP+ solution):
include <shldisp.h>
IShellDispatch4 *pShell;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER,
IID_IShellDispatch, (void**)&pShell);
if(SUCCEEDED(hr))
pShell->WindowsSecurity();
CoUninitialize();
The only solution to invoke it from the local desktop is to use SASLib. It's not public. Write a note to saslib#microsoft.com to request it.
EDIT: Wait! You want to lock the machine? Just call LockWorkStation()! Click the link for more info about header file, lib file et all other details.
Since VNC can let you do this to a remote system, it must be possible. If I were you, I'd trawl through the source to UltraVNC. Then I'd post the answer the here :)
Do you need to send control+alt+delete or do you just want to bring up the task manager?
If you just need to bring up the task manager you can simply run \Windows\System32\taskmgr.exe
I know it's an old questions but I am posting my solutions here in case someone looking for a solution arrives here. The part1 and part2 articles explain how Winlogon registers the CAD sequence and provides code examples on how to use it.
Send CAD and Unlock workstation for Windows XP - Part 1 (free)
Send CAD and Unlock workstation for Windows XP - Part 2 (free)
SasLibEx for Vista and higher (sorry, this is not free)
Wouldn't it be easier to just ask the machine to shut down or logout? That key combination isn't really a good idea? You can send these messages.
Can't you start a screensaver and it will take care of the locking for you? I don't have a Windows machine available right now, but I recall one could lock the workstation like this.
Call the SendSAS function to achieve this.

Resources