Solved

Get the process ID after start a service

Posted on 1997-12-10
16
256 Views
Last Modified: 2013-12-03
I am using VC++5.0 in NT.

I start a service through SCM. How can I get the process ID and other information of the service I start in programming level?

Thanks.

Mike
0
Comment
Question by:mikechen
  • 9
  • 3
  • 2
  • +1
16 Comments
 
LVL 1

Expert Comment

by:Tiutin
Comment Utility

/******************************************************************************\
*       This is a part of the Microsoft Source Code Samples.
*              Copyright (C) 1994-1995 Microsoft Corporation.
*       All rights reserved.
*       This source code is only intended as a supplement to
*       Microsoft Development Tools and/or WinHelp documentation.
*       See these sources for detailed information regarding the
*       Microsoft samples programs.
\******************************************************************************/

/*++

Copyright (c) 1994  Microsoft Corporation

Module Name:

    tlist.c

Abstract:

    This module implements a task list application.

--*/

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"


#define MAX_TASKS           256

#define PrintTask(idx) \
        printf( "%4d %-16s", tlist[idx].dwProcessId, tlist[idx].ProcessName ); \
        if (tlist[idx].hwnd) { \
            printf( "  %s", tlist[idx].WindowTitle ); \
        } \
        printf( "\n" );


DWORD numTasks;
TASK_LIST tlist[MAX_TASKS];

VOID Usage(VOID);


int _cdecl
main(
    int argc,
    char *argv[]
    )

/*++

Routine Description:

    Main entrypoint for the TLIST application.  This app prints
    a task list to stdout.  The task list include the process id,
    task name, ant the window title.

Arguments:

    argc             - argument count
    argv             - array of pointers to arguments

Return Value:

    0                - success

--*/

{
    DWORD          i;
    TASK_LIST_ENUM te;
    BOOL fTree;

    if (argc > 1 && (argv[1][0] == '-' || argv[1][0] == '/') && argv[1][1] == '?') {
        Usage();
    }

    fTree = FALSE;

    //
    // Obtain the ability to manipulate other processes
    //
    EnableDebugPriv();

    //
    // get the task list for the system
    //
    numTasks = GetTaskList( tlist, MAX_TASKS );

    //
    // enumerate all windows and try to get the window
    // titles for each task
    //
    te.tlist = tlist;
    te.numtasks = numTasks;
    GetWindowTitles( &te );

    //
    // print the task list
    //
    for (i=0; i<numTasks; i++) {
      PrintTask( i );
    }

    //
    // end of program
    //
    return 0;
}

VOID
Usage(
    VOID
    )

/*++

Routine Description:

    Prints usage text for this tool.

Arguments:

    None.

Return Value:

    None.

--*/

{
    fprintf( stderr, "Microsoft (R) Windows NT (TM) Version 3.5 TLIST\n" );
    fprintf( stderr, "Copyright (C) 1994-1995 Microsoft Corp. All rights reserved\n\n" );
    fprintf( stderr, "usage: TLIST\n" );
    ExitProcess(0);
}

0
 

Author Comment

by:mikechen
Comment Utility
Thanks for your response, Tiutin.

I need something specific for NT-Service. After I start it, I hope I can get its information precisely. To walk through all the tasks in the system may not what I want.

Thanks again.

0
 
LVL 1

Expert Comment

by:Tiutin
Comment Utility
Just a question. Do you need all the process properties listed below?
=========================
Process Properties for Windows NT

Module Name - The name of the module.

Process ID - The unique ID of this process. Process ID numbers are reused, so they identify a process only for the lifetime of that process. The Process object type is created when a program is run. All the threads in a process share the same address space and have access to the same data.

Priority Base - The current base priority of this process. Threads within a process can raise and lower their own base priority relative to the process's base priority.

Threads - The number of threads currently active in this process.

CPU Time - Total CPU time spent on this process and its threads. Equal to User Time plus Privileged Time.

User Time - The cumulative elapsed time that this process's threads have spent executing code in User Mode in non-idle threads. Applications execute in User Mode, as do subsystems such as the window manager and the graphics engine.

Privileged Time - The total elapsed time this process has been running in Privileged Mode in non-idle threads. The service layer, the Executive routines, and the Kernel execute in Privileged Mode. Device drivers for most devices other than graphics adapters and printers also execute in Privileged Mode. Some work that Windows does for your application may appear in other subsystem processes in addition to Privileged Time.

Elapsed Time - The total elapsed time this process has been running.

Virtual Bytes - The current size (in bytes) of the virtual address space the process is using. The use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. However, virtual space is finite, and using too much may limit the ability of the process to load libraries.

Peak Virtual Bytes - The maximum number of bytes of virtual address space the process has used at any one time.

Working Set - The set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from the Working Set. If they are needed, they will be soft-faulted back into the Working Set before they leave main memory.

Peak Working Set - The maximum number of pages in the working set of this process at any point in time.

Paged Pool Bytes - The current amount of paged pool the process has allocated. Paged pool is a system memory area where operating system components acquire space as they accomplish their appointed tasks. Paged pool pages can be paged out to the paging file when not accessed by the system for sustained periods of time.

Nonpaged Pool Bytes - The current number of bytes in the nonpaged pool allocated by the process. The nonpaged pool is a system memory area where space is acquired by operating system components as they accomplish their appointed tasks. Nonpaged pool pages cannot be paged out to the paging file; they remain in main memory as long as they are allocated.

Private Bytes - The current number of bytes this process has allocated that cannot be shared with other processes.

Free Bytes - The total unused virtual address space of this process.

Reserved Bytes - The total amount of virtual memory reserved for future use by this process.

Free Image Bytes - The amount of virtual address space that is not in use or reserved by images within this process.

Reserved Image Bytes - The sum of all virtual memory reserved by images run within this process.

Page File Bytes - The current number of pages that this process is using in the paging file. The paging file stores pages of data used by the process but not contained in other files. The paging file is used by all processes, and lack of space in the paging file can cause errors while other processes are running.

Peak Page File Bytes - The maximum number of pages that this process has used in the paging file.

Page Faults - The number of page faults by the threads executing in this process. A page fault occurs when a thread refers to a virtual memory page that is not in its working set in main memory. Thus, the page will not be retrieved from disk if it is on the standby list and hence already in main memory, or if it is being used by another process with which the page is shared.

Show For Space Marked As - Use this list box to select the category of space (image, mapped, reserved, or unassigned).

Executable Bytes - For the selected category, the sum of all the address space that this process is using. Executable memory is memory that can be executed by programs, but may not be read or written.

Exec-Read-Only Bytes - For the selected category, the sum of all the address space in use with read-only properties that this process is using. Exec-read-only memory is memory that can be executed as well as read.

Exec-Read-Write Bytes - For the selected category, the sum of all the address space in use with read-write properties that this process is using. Exec-read-write memory is memory that can be executed by programs as well as read and modified.

Exec-Write-Copy Bytes - For the selected category, the sum of all the address space that can be executed by programs as well as read and written. This type of protection is used when memory needs to be shared between processes. If the sharing processes only read the memory, then they will all use the same memory. If a sharing process desires write access, then a copy of this memory will be made for the process.

No-Access Bytes - For the selected category, the sum of all the address space that prevents a process from using it. An access violation is generated if writing or reading is attempted.

Read-Only Bytes - For the selected category, the sum of all the address space that can be executed as well as read.

Read-Write Bytes - For the selected category, the sum of all the address space that allows reading and writing.

Write-Copy Bytes - For the selected category, the sum of all the address space that allows memory sharing for reading but not for writing. When processes are reading this memory, they can share the same memory. However, when a sharing process wants to have read/write access to this shared memory, a copy of that memory is made for writing.
0
 

Author Comment

by:mikechen
Comment Utility
Actually, I need only Module Name and Process ID.

Thank you very much.
0
 

Author Comment

by:mikechen
Comment Utility
Actually, I need only Module Name and Process ID.

Thank you very much.
0
 

Author Comment

by:mikechen
Comment Utility
One more thing, I guess the Process ID is enough.

Thank you.


Mike

0
 
LVL 1

Expert Comment

by:ete
Comment Utility
When you start a service executable through SCM, the SCM starts the executable and the main() function of the service exe sets the ServiceTable entry and calls the StartServiceCtrlDispatcher() API as you know. This means, that the PID of service exe is directly known only by SCM.

The point is that the main() function of service exe is just a loader to get the code into memory. Through ServiceTable SCM knows the name of the "ServiceMain", which in turn is loaded and executed in the SCM memory space. So unfortunately the PID of the started service would not help much, the real code is executed in another memory space and in another process.

If you clarify what you want to achieve, I could try to figure out a solution...


0
 

Author Comment

by:mikechen
Comment Utility
Thank you very much, Ete.

OK, I need to implemente an NT-Service to start/stop several NT-Service/Applications in the same NT box. After that, I need to stop them per requests from some other application.

Generally speaking, the NT-Service/Application started by my program should be able to shutdown gracefully. I just try to prepare for the worst case. If they fail to shutdown gracefully, I have to terminate them. So, I need to call TerminateProcess() to do that. For an application, no problem. Since I call CreateProcess() to start it. But for NT-Service, I have some difficulty. That is the reason I post this message.

Thanks in advance.

Mike
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Expert Comment

by:ete
Comment Utility
Mike, let's see if I understood you correctly:

- you wrote a service to start other services and normal apps
- other apps can ask your service to stop any of the started apps or services
- normal apps started by your service you can kill with TerminateProcess()
- you want to to kill badly behaving services also with TerminateProcess()

If this scenario is a proper interpretation, you have perhaps a small misunderstanding in SCM context. You cannot and must not terminate a service in any other means than through SCM interface by using ControlService() API.

In a logical sense services can be compared to device drivers. They must respect the interface rules, if not they are buggy/misbehaving and should not be used in production environment.

For the normal apps your service started you can do what ever you prefer, but for services stay strictly in puritan SCM interface.

regards,
ETE


0
 

Author Comment

by:mikechen
Comment Utility
Thank you very much, Ete.

Actually, the way I terminate a service is through SCM interface first. Then I try to wait a certain amount of time. If that process is still there, I have to kill it.

I am not sure whether you have this experience: You go to the SCM interface(setting/control panel/services) and try to stop a service and you get a error message. You can never stop that service through that interface, even you use End Process button. But you can always go to DOS Command Prompt and use "kill" command to stop it. I believe "kill" calls TerminateProcess(). So, again, in the normal situation, the service should be gone gracefully. I am just preparing the worst situation.

Any new idea ?

Thanks again.
0
 
LVL 3

Expert Comment

by:stefanr
Comment Utility
I have written an application that monitors a set of services to be able to restart any service that dies prematurely. In the process I used the SCM to enumerate the services, the Performance Library to retrieve the process ID:s, and with that ID I am able to open a process handle to the service. I do also need a process token to adjust some privileges to be able to kill the service. Then I optionally let the program try to restart the service. The basic principle is to compare the list of processes with the Service Control Manager's list of running services. If they don't match, there is some error.

Hope that will give you some ideas how to proceed.

Happy New Year,
/Stefan
0
 

Author Comment

by:mikechen
Comment Utility
Hi, Stefan.

Thank you very much for your response.

When you "compare the the list of processes with the Service Control Manager's list of running services", what do you base on ? The name or the process or something else ?

Also, you mention performance API. What are they ?

Thanks again and happy new year.


Mike

0
 
LVL 3

Expert Comment

by:stefanr
Comment Utility
Hi, Mike!

Well, basically I use a CMap when I enumerate the services in the SCM database. As the key I use the service name. Based on that I use the Performance Library, which is a psuedo registry key holding the real time status of various things, among these all processes in the system. Using the Performance Library I make a "snapshot" at regular intervals of the system status at that specific time, obtaining all processes, including the module names. That name is the key value to my CMap.

The Performance Library is rather complicated, so I recommend you to search for "performance data" (you can also look for "performance data helper", but I haven't used it). The Performance Data retrieved from the psuedo registry key is packed in a very specific format, and you have to unpack it to get the information you need.

Good luck!

/Stefan
0
 

Author Comment

by:mikechen
Comment Utility
Hi, Stefan.

Thank you for your response. If you don't mind, would you please lock this question ?

Thanks again.

Mike
0
 
LVL 3

Accepted Solution

by:
stefanr earned 50 total points
Comment Utility
Locked the question as requested.
/Stefan
0
 

Author Comment

by:mikechen
Comment Utility
Thank you, Stefanr.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article describes how to add a user-defined command button to the Windows 7 Explorer toolbar.  In the previous article (http://www.experts-exchange.com/A_2172.html), we saw how to put the Delete button back there where it belongs.  "Delete" is …
This article surveys and compares options for encoding and decoding base64 data.  It includes source code in C++ as well as examples of how to use standard Windows API functions for these tasks. We'll look at the algorithms — how encoding and decodi…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now