473,713 Members | 2,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Service Terminating Itself

I have a C# Windows Service running as the NetworkService account because it
needs to access a network share.

As part of the service's initialization, I want the service to terminate, if
an unrecoverable error occurs. When that case occurs, I create a
ServiceControll er object and call the Stop() method.

However - I get an exception thrown saying access denied. If I switch to
using the LocalService account it works fine, but I lose access to my
network resources.

What is the proper way for a service to stop itself? I would really rather
not add a separate user account to accomplish this. It seems kind of odd
that a service cannot stop itself.
Any ideas?

--
Adam Clauss

Nov 17 '05
23 7584

"Wessel Troost" <no*****@like.t he.sun> wrote in message
news:op.suc2l7k pf3yrl7@asbel.. .
Note that above assumes you didn't modify the DACL for the service object
(something only administrator can do).
The service doesn't need SERVICE_START or SERVICE_STOP privileges to stop
itself. It can just call SetServiceStatu s(), which is allowed regardless
of access privileges. The service can call this only to report its own
status, something which every service must do.


Ok, I see your point, you aren't discussing services based on the FCL. The
framework (v1.x) lacks this level of control, that is you - can't call
SetServiceStatu s at all, because they implemented the ServiceBase class to
follow (somewhat too strictly) the SCM interface protocol. That imposes a
problem when you need to abruptly shutdown a service without being requested
y the SCM.
Now, this is something that is taken care of in v2.0 through a method
ServiceBase.Sto p(), which calls OnStop() followed by a call to
SetServiceStatu s() with the SERVICE_STOPPED status set, followed by the
"Service stopped succesfuly" message written to the eventlog. When the
service is hosted, the AppDomain is unloaded before Stop() returns, then
it's up to the host to ExitProcess or do something else. If the service
isn't hosted, and there are no other active Services in the process, the
process exits through the normal CLR shutdown procedure, else the process
keeps running in the ServiceControlD ispatcher.

Another change makes is the possible to extend the start and stop period, by
allowing to hint the SCM (START_PENDING etc...) when there are pending
requests.
Or in short Service applications must conform to the interface rules of
the
SCM, and this can only be guaranteed if both controller and service are
separate applications.

Earlier we agreed (and the OP said) that his service could stop itself, if
it ran as local system?


Yes, but not as local service or network service, which are the prefered
accounts.
There are many services that require local system privileges. Actually,
one of the main reasons for writing a service used to be increased
privileges.


I have to disagree, services should run according the principle of least
privilege, just like any other application in the system at least if you
care about security.
Too many services are running with system privileges, something that MSFT
also recognizes, and something they'll change in Longhorn (or Windows
VISTA).
of the process shutdown. You see no ExitProcess called ever.

Kind of a technicality really, but how do you think a userspace process
signals to the OS that it wants to stop?

When the Main() thread exits, the CLR will call ExitProcess().


That's what I meant with :
<and the CLR handles the remaining of the process shutdown.>
I know the CLR calls ExitProcess (it might even call TerminateProces s), what
I mean't was that user code (your code and the FCL) should never call
ExitProcess, and as the FCL never call's it, you won't see ExitProcess ever
called.

- You might disturb the SCM!


The SCM can handle crashing services. In fact, I've killed tons of
services during development using TerminateProces s(), which is arguably
worse than ExitProcess(). The SCM never became disturbed.

During development, right. But, ever killed services on a production server
running MS cluster server with potentially 5000++ users logged on?
The SCM doesn't guarantee to handle crashing services, it's not designed to
handle it, you might have done it several times without a problem, but that
doesn't mean it's common practice, all depends on the type of service, it
might fail and disturb the SCM. In short "killing" services is a bad
practice, just run "net stop servicename" to stop them, if this fails you
have a bug in your code which must be solved before you can call this
program a 'Service'.

- you might have other services running in the process AND,
- your service might have dependent services running and these must be
stopped before your service stops.

I agree that a service should exit nicely in these circumstances.

Sure, and the CLR makes things even more constrained, there are a number of
OS services that should never be called from managed code (and IMO these
services shouldn't even been exposed to managed code at all), Thread.Abort
is just one of them, Thread.Resume and Thread.Interupt are even been removed
fom v2.0.

Nov 17 '05 #21
> Ok, I see your point, you aren't discussing services based on the FCL.
Yeah. At some point I wrote "We can agree to disagree about wether a
C++ ATL service could.", and you replied "Sorry but I have to disagree.",
so I went on talking non-FCL after that.
I have to disagree, services should run according the principle of least
privilege, just like any other application in the system at least if you
care about security.
Agreed, my point was that if you really need higher privileges, a service
used to be the way to do it.
I mean't was that user code (your code and the FCL) should never call
ExitProcess, and as the FCL never call's it, you won't see ExitProcess
ever called.
Yeah.
During development, right. But, ever killed services on a production
server running MS cluster server with potentially 5000++ users logged on?
Haha, not 5000++ no, but over 100, sure. If your alternative is a reboot,
killing a service is the lower-impact option.
have a bug in your code which must be solved before you can call this
program a 'Service'.
I hope you're not saying that a 'Service' has to be bug-free. Terms like
"bug free program", "first-time right development", "fixed requirements"
are the telltale signs of a newbie project leader :)

Certainly a C++ service can be expected to crash the hard way. One of the
nice things about .NET is that it's very stable in the crashing
department. I've never seen a pure .NET program segfault.
Sure, but not in managed world (see above) where you don't have that
kind of
flexibility you have when programming against the low level Win32 API's.
This is the price you pay for simplicity, you can (to) quicly build a
windows service using the framework (didn't you notice the recent
Windows Service boom), but I seriously doubt this is a good thing.

Hmm, what's bad about simple services? They can start automaticcaly
after an "automatic update reboot". That's pretty nice for a background
program.

It also looks more professional. System operators prefer Services to a
simple Forms/Console application that does exactly the same thing.

Greetings,
Wessel
Nov 17 '05 #22
Inline
"Wessel Troost" <no*****@like.t he.sun> wrote in message
news:op.sue1gnp wf3yrl7@asbel.. .
Ok, I see your point, you aren't discussing services based on the FCL. Yeah. At some point I wrote "We can agree to disagree about wether a C++
ATL service could.", and you replied "Sorry but I have to disagree.", so
I went on talking non-FCL after that.
I have to disagree, services should run according the principle of least
privilege, just like any other application in the system at least if you
care about security.


Agreed, my point was that if you really need higher privileges, a service
used to be the way to do it.

That doesn't mean it should run as SYSTEM, create a local service account
and grant the privileges he needs and enable the privilege in code, but
please don't put your service in the TCB, at least not on XP or higher. I
know W2K needs this to call LogonUser, but higher OS'ses don't need this
privilege any longer. Note also that on W2K3 and XP SP2, you cannot call
CreateProcessWi thLogonW when running as Localsystem.
I mean't was that user code (your code and the FCL) should never call
ExitProcess, and as the FCL never call's it, you won't see ExitProcess
ever called.

Yeah.
During development, right. But, ever killed services on a production
server running MS cluster server with potentially 5000++ users logged on?

Haha, not 5000++ no, but over 100, sure. If your alternative is a reboot,
killing a service is the lower-impact option.

What's the difference 100 or 5000, killing a service that might crash other
services, or in the case of cluster server might crash the cluster service,
is defenately worse than a reboot of a single node.
have a bug in your code which must be solved before you can call this
program a 'Service'.

I hope you're not saying that a 'Service' has to be bug-free. Terms like
"bug free program", "first-time right development", "fixed requirements"
are the telltale signs of a newbie project leader :)

No, I'm in this business for 35 years now, I know that software is bug-free
until the first bug shows up. I say that it's clearly a bug when you can't
stop a service. and it's the kind of bug you should correct before the bugs
in the 'service' code, unless they are closely related. I've seen to many
services that run correctly otherwise but had problems to stop or didn't do
the right thing when stopping (process that keep running when the service
was stopped). One of the popular answers I heard was "services are designed
to run" not to stop.
I agree that not all services can/should be bullet proof, but at least when
they fail they should fail in a correct way, or to put it differently - they
should be as failsafe as possible (asp.net is one example of a fails safe
hosted service).
Especially business critical services that run on large boxes or in a
cluster should be designed such that they are fully controlled from the
outside, that is from the cluster manager (note that you shouldn't even use
the Services applet in a cluster case). They should also be designed to
correctly report their status when asked for, and they should be prepared to
fail over when they don't reply on the status requests.

Certainly a C++ service can be expected to crash the hard way. One of the
nice things about .NET is that it's very stable in the crashing
department. I've never seen a pure .NET program segfault.

Define a pure .NET program, never used PInvoke to call into native code and
have your arguments defined or the calling convention incorrectly? Sure the
message wouldn't look like a segfault, but a silently dying thread or
"execution engine error" leaving no trace in your logfile and he! its' a
service, so no user message on the destop either. Note that this is another
major problem in .NET, too much PInvoke using the wrong calling convention,
or passing incorrect types. This kind of error doesn't show up at the first
call (thanks to the hacks in the CLR that try to correct the calling
convention mistakes in user code), but it shows up only after hours or days
maybe, not a pretty face when this happens to a service and certainly not
easy to debug.
Sure, but not in managed world (see above) where you don't have that
kind of
flexibility you have when programming against the low level Win32 API's.
This is the price you pay for simplicity, you can (to) quicly build a
windows service using the framework (didn't you notice the recent
Windows Service boom), but I seriously doubt this is a good thing.

Hmm, what's bad about simple services? They can start automaticcaly
after an "automatic update reboot". That's pretty nice for a background
program.

A lot of them shouldn't run as a service but as a scheduled task, and don't
forget that the number of services are restricted in Windows (OS version
dependent). That's why I called it a "service boom", in my daily consultancy
job for a large company it became one of the most irritating questions to
ask - how many services are you running by now. The answers go leke; huh..
don't know, it doesn't matter it runs in the background at a lower
priortity; or the service is only actively running once a day for a couple
of minutes.
It also looks more professional. System operators prefer Services to a
simple Forms/Console application that does exactly the same thing.

Sure, and they want the service to have a UI too ;-). which is just another
problem source since the intro of .NET. (not .NET fault though).

Greetings,
Willy.
Nov 17 '05 #23
> No, I'm in this business for 35 years now, I know that software is

Cheers :)

And I agree with the rest of your post.

Greetings,
Wessel
Nov 17 '05 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
7268
by: SP | last post by:
Hi All, I wrote a windows service which is supposed to stop after specified amount of time. I am calling OnStop() after specified time. OnStop() methods executed but I dont see the service stopping. Please advise how to stop the service. Thanks, SP
8
1428
by: Jerry Camel | last post by:
I want my service to terminate automatically if the specified parameters are invalid. I tried to use a servicecontroller component to attach to the service, but I think that it's failing because it's being called in the OnStart event (where I validate the parameters) and the service isn't fully running yet. How can I stop my service from within the service itself? Thanks. Jerry
20
1419
by: Lee Schipper | last post by:
If a service needs to shut itself down, say due to a fatal error detected in the program, what is the cleanest way to do that? Can I simply use the Visual Basic End statement? I only have a single service running in my process. Thanks!
0
2052
by: Kevin | last post by:
I'm writing a service in VB.NET. Reference the following code: Dim oStreamWriter As StreamWriter .... .... .... oStreamWriter = File.CreateText(TempLogFile) If Err.Number <> 0 Then EventLog.WriteEntry("LogService", "Error Creating Log File: " & _ TempLogFile & vbCrLf & _
0
8795
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9009
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7942
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6621
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5943
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4462
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4715
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2103
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.