Recent

Author Topic: [SOLVED] How to kill a specific instance of a program?  (Read 4071 times)

Hartmut

  • Hero Member
  • *****
  • Posts: 749
[SOLVED] How to kill a specific instance of a program?
« on: July 24, 2018, 01:34:08 pm »
My program (a console application) can run twice at the same time. I want the ability that the 2nd instance can kill the 1st instance. Both instances have been started by the command line (not one by each other).

What I have is how to kill a process with a certain PID. To get the PID of a program I found this:
http://wiki.lazarus.freepascal.org/Windows_Programming_Tips#Showing.2Ffinding_processes
and improved it to return an array with multiple PIDs for 1 program, if multiple instances are running.

My problem now is, that if 2 instances are running, then I get 2 PIDs for them and do not know which is which.
So my idea is, that the 2nd instance somehow shall determine it's own PID. Then the other PID must be from instance #1 and can be killed.
How can this be done?

I use FPC 3.0.4 on Windows 7 32 bit. Thanks in advance.
« Last Edit: July 24, 2018, 02:01:52 pm by Hartmut »

balazsszekely

  • Guest
Re: How to kill a specific instance of a program?
« Reply #1 on: July 24, 2018, 01:41:39 pm »
Quote
So my idea is, that the 2nd instance somehow shall determine it's own PID. Then the other PID must be from instance #1 and can be killed.
Add windows to the uses list, then call GetCurrentProcessId function:
Code: Pascal  [Select][+][-]
  1. uses
  2.   Windows,
  3.   ....
  4.   { you can add units after this };
  5.  
  6. begin
  7.   Writeln(GetCurrentProcessId);
  8.   Readln;
  9. end.

Hartmut

  • Hero Member
  • *****
  • Posts: 749
Re: How to kill a specific instance of a program?
« Reply #2 on: July 24, 2018, 02:01:27 pm »
That's a perfect solution. Thank you very much for your help.

ASerge

  • Hero Member
  • *****
  • Posts: 2241
Re: How to kill a specific instance of a program?
« Reply #3 on: July 25, 2018, 01:58:57 am »
The System unit already has this function:
Code: Pascal  [Select][+][-]
  1. {$APPTYPE CONSOLE}
  2. begin
  3.   Writeln(GetProcessID);
  4.   Readln;
  5. end.

Hartmut

  • Hero Member
  • *****
  • Posts: 749
Re: [SOLVED] How to kill a specific instance of a program?
« Reply #4 on: July 25, 2018, 06:08:22 pm »
Thank you ASerge for that information, which is platform independend.

 

TinyPortal © 2005-2018