Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2006.07.23;
Скачать: [xml.tar.bz2];

Вниз

Как остановить запущенный процесс   Найти похожие ветки 

 
koha   (2006-07-04 12:57) [0]

Как остановить запущенный процесс?
Почему то при использовании функции ExitProcess(ProcessInfo.hProcess); Прекращает работу основное приложение, которое запускает дочерний процесс, а запущенный процесс остается работать.
К тому же нет возможности использовать способ:

if FindWindow(PChar("Form Class"),PChar("мастер установки")) <> 0 then
begin
 h:=FindWindow(PChar("Form Class"),PChar("мастер установки"));
 PostMessage(h,WM_QUIT,1,0);
 //или
 PostMessage(h,WM_CLOSE,0,0);
end;


 
Игорь Шевченко ©   (2006-07-04 13:35) [1]


> Как остановить запущенный процесс?


TerminateProcess


 
koha   (2006-07-04 14:07) [2]

> Игорь Шевченко

TerminateProcess - имеет два параметра
1 - hProcess: Cardinal;
2 - uExitCode: Cardinal;

С первым вроде понятно, а совторым не все понятно - какй должен быть uExitCode. Такой как ниже приведен почемо то не работает.
TerminateProcess(ProcessInfo.hProcess,WM_QUIT);


 
Ega23 ©   (2006-07-04 14:12) [3]


The TerminateProcess function terminates the specified process and all of its threads.

BOOL TerminateProcess(

   HANDLE hProcess, // handle to the process
   UINT uExitCode  // exit code for the process  
  );


Parameters

hProcess

Identifies the process to terminate.
Windows NT: The handle must have PROCESS_TERMINATE access. For more information, see Process Objects.

uExitCode

Specifies the exit code for the process and for all threads terminated as a result of this call. Use the GetExitCodeProcess function to retrieve the process"s exit value. Use the GetExitCodeThread function to retrieve a thread"s exit value.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The TerminateProcess function is used to unconditionally cause a process to exit. Use it only in extreme circumstances. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.
TerminateProcess causes all threads within a process to terminate, and causes a process to exit, but DLLs attached to the process are not notified that the process is terminating.

Terminating a process causes the following:

1. All of the object handles opened by the process are closed.
2. All of the threads in the process terminate their execution.
3. The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.
4. The states of all threads of the process become signaled, satisfying any threads that had been waiting for the threads to terminate.
5. The termination status of the process changes from STILL_ACTIVE to the exit value of the process.



Terminating a process does not cause child processes to be terminated.
Terminating a process does not necessarily remove the process object from the system. A process object is deleted when the last handle to the process is closed.


Где ты тут увидел WM_QUIT?


 
koha   (2006-07-04 14:33) [4]

> Где ты тут увидел WM_QUIT? - Это что попало-первое в голову взбрело.


 
Ega23 ©   (2006-07-04 14:37) [5]


> Это что попало-первое в голову взбрело.


Бог в помощь.
Попробуй заодно подставить Application, TButton.Create(nil) и 34.


 
koha   (2006-07-04 15:00) [6]

Заработало!!!!
Вножное место вставил
........................
while WaitForSingleObject(ProcessInfo.hProcess, 0) = WAIT_TIMEOUT do
begin
  Application.ProcessMessages;
  Sleep(50);
  if SetupNext=false then
    TerminateProcess(ProcessInfo.hProcess,PROCESS_TERMINATE);
     // -это должно было стоять сдесь, а не в отдельной процедуре типа:
     // .... TForm1.BreakAll_BtnClick....
end;
..........................


 
koha   (2006-07-04 15:11) [7]

Спасибо Игорь Шевченко, aga23!
Так под чутким наставлением на путь истинный можно и самому когда-нибудь стать из верных "послушников" "Мастером Джидаем".


 
Desdechado ©   (2006-07-04 16:02) [8]

Чтобы стать мастером-джедаем, нужно быть внимательным и думать головой, а не "В ножное место вставил". А то так и будешь в то место вставлять...

> TerminateProcess(ProcessInfo.hProcess,PROCESS_TERMINATE);
Увидел константу большими буквами и решил снова влепить абы что?
ну-ну


 
koha ©   (2006-07-04 16:14) [9]

Не просто увидел большими буквами, а успел прошариться и здесь:

unit Windows;
//........................
 PROCESS_TERMINATE         = $0001;
 {$EXTERNALSYM PROCESS_TERMINATE}
 PROCESS_CREATE_THREAD     = $0002;
 {$EXTERNALSYM PROCESS_CREATE_THREAD}
 PROCESS_VM_OPERATION      = $0008;
 {$EXTERNALSYM PROCESS_VM_OPERATION}
 PROCESS_VM_READ           = $0010;
 {$EXTERNALSYM PROCESS_VM_READ}
 PROCESS_VM_WRITE          = $0020;
 {$EXTERNALSYM PROCESS_VM_WRITE}
 PROCESS_DUP_HANDLE        = $0040;
 {$EXTERNALSYM PROCESS_DUP_HANDLE}
 PROCESS_CREATE_PROCESS    = $0080;
 {$EXTERNALSYM PROCESS_CREATE_PROCESS}
 PROCESS_SET_QUOTA         = $0100;
 {$EXTERNALSYM PROCESS_SET_QUOTA}
 PROCESS_SET_INFORMATION   = $0200;
 {$EXTERNALSYM PROCESS_SET_INFORMATION}
 PROCESS_QUERY_INFORMATION = $0400;
 {$EXTERNALSYM PROCESS_QUERY_INFORMATION}
 PROCESS_ALL_ACCESS        = (STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $FFF);
 {$EXTERNALSYM PROCESS_ALL_ACCESS}
//........................


И сюда заглянуть:

Platform SDK Release: February 2003  What did you think of this topic?
Order a Platform SDK CD

Value Meaning
PROCESS_ALL_ACCESS All possible access rights for a process object.
PROCESS_CREATE_PROCESS Required to create a process.
PROCESS_CREATE_THREAD Required to create a thread.
PROCESS_DUP_HANDLE Required to duplicate a handle using DuplicateHandle.
PROCESS_QUERY_INFORMATION Required to retrieve certain information about a process, such as its exit code and priority class (see GetExitCodeProcess and GetPriorityClass).
PROCESS_SET_QUOTA Required to set memory limits using SetProcessWorkingSetSize.
PROCESS_SET_INFORMATION Required to set certain information about a process, such as its priority class (see SetPriorityClass).
PROCESS_TERMINATE Required to terminate a process using TerminateProcess.
PROCESS_VM_OPERATION Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
PROCESS_VM_READ Required to read memory in a process using ReadProcessMemory.
PROCESS_VM_WRITE Required to write to memory in a process using WriteProcessMemory.
SYNCHRONIZE Required to wait for the process to terminate using the wait functions
.


 
Desdechado ©   (2006-07-04 16:27) [10]

Могу ошибаться, но в "The handle must have PROCESS_TERMINATE access." речь идет о правах на процесс HANDLE hProcess.


 
Ketmar ©   (2006-07-04 16:33) [11]

ответ на все вопросы -- 42.


 
koha ©   (2006-07-04 17:25) [12]

> Desdechado

> Могу ошибаться, но в "The handle must have PROCESS_TERMINATE access."  > речь идет о правах на процесс HANDLE hProcess.

Полная страница:

Process Security and Access Rights

The Windows NT security model enables you to control access to process objects. For more information about security, see Access-Control Model.

When a user logs in, the Microsoft® Windows® operating system collects a set of data that uniquely identifies the user during the authentication process, and stores it in an access token. This access token describes the security context of all processes associated with the user. The security context of a process is the set of credentials given to the process or the user account that created the process.

You can specify a security descriptor for a process when you call the CreateProcess, CreateProcessAsUser, or CreateProcessWithLogonW function. If you specify NULL, the process gets a default security descriptor. The ACLs in the default security descriptor for a process come from the primary or impersonation token of the creator.

To retrieve a process"s security descriptor, call the GetSecurityInfo function. To change a process"s security descriptor, call the SetSecurityInfo function.

The valid access rights for process objects include the DELETE, READ_CONTROL, SYNCHRONIZE, WRITE_DAC, and WRITE_OWNER standard access rights, in addition to the following process-specific access rights.

Value Meaning
PROCESS_ALL_ACCESS All     possible access rights for a process object.
PROCESS_CREATE_PROCESS     Required to create a process.
PROCESS_CREATE_THREAD      Required to create a thread.
PROCESS_DUP_HANDLE         Required to duplicate a handle using DuplicateHandle.
PROCESS_QUERY_INFORMATION  Required to retrieve certain information about a process, such as its exit code and priority class (see GetExitCodeProcess and GetPriorityClass).
PROCESS_SET_QUOTA          Required to set memory limits using SetProcessWorkingSetSize.
PROCESS_SET_INFORMATION    Required to set certain information about a process, such as its priority class (see SetPriorityClass).
PROCESS_TERMINATE          Required to terminate a process using TerminateProcess.
PROCESS_VM_OPERATION       Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
PROCESS_VM_READ            Required to read memory in a process using ReadProcessMemory.
PROCESS_VM_WRITE           Required to write to memory in a process using WriteProcessMemory.
SYNCHRONIZE                Required to wait for the process to terminate using the wait functions.

The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object. When you call the OpenProcess function, the system checks the requested access rights against the DACL in the process"s security descriptor. When you call the GetCurrentProcess function, the system returns a pseudohandle with the maximum access that the DACL allows to the caller.

You can request the ACCESS_SYSTEM_SECURITY access right to a process object if you want to read or write the object"s SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.

Warning  A process that has some of the access rights noted here can use them to gain other access rights. For example, if process A has a handle to process B with PROCESS_DUP_HANDLE access, it can duplicate the pseudo handle for process B. This creates a handle that has maximum access to process B. For more information on pseudo handles, see GetCurrentProcess.

Platform SDK Release: February 2003


 
koha ©   (2006-07-04 19:52) [13]

Все другие запущенные процессы прекращаются, но почему-то запущенный "мастер установки пакета обновления
Windows XP", например KB890175 "не гаснет", как буд-то для него не дейтвует функция TerminateProcess
Немогу разобраться почему?


 
Leonid Troyanovsky ©   (2006-07-04 20:09) [14]


> koha ©   (04.07.06 19:52) [13]

> Немогу разобраться почему?


Потому, как малограмотен,
хотя, уже и злоумышленник.

Иди, иди отсель, болезный, с Богом.

--
Regards, LVT.


 
koha ©   (2006-07-04 20:23) [15]

> Leonid Troyanovsky
> хотя, уже и злоумышленник.

Никакой не злоумышленник, а делаю благую невинную прогу, которая всего лишь должна облегчить бренный труд админа - не кликать же каждый пакет обновления в ручную, прога должна трудиться автоматически ставить все пакеты один за другим, а админ честно дремать.


 
Leonid Troyanovsky ©   (2006-07-04 20:33) [16]


> koha ©   (04.07.06 20:23) [15]

> должна трудиться автоматически ставить все пакеты один за
> другим, а админ честно дремать.


Я ж и говорю - зловредная прога.
Админ не пожарный, чтоб столько спать, ему надо быть в тонусе.
И пусть уж он будет в ем.

--
Regards, LVT.


 
koha ©   (2006-07-04 20:50) [17]

> Leonid Troyanovsky

Что выгоняете уже, надоел уже что ли? Я ж только чуть -чуть, только из
любопытства, я даже не хотел вроде как. А кто ж неразумного научит?


 
Leonid Troyanovsky ©   (2006-07-04 22:31) [18]


> koha ©   (04.07.06 20:50) [17]

> любопытства, я даже не хотел вроде как.


Чисто из любопытства, подзащитный просто хотел
посмотреть, что у меня внутри.
..

Допустим, что вот этот блондин хорошо играет в шахматы,
а этот брюнет - не очень. И, никакие лекции не изменят
этого положения. Если, конечно,  мы, каждый день,
каждый час, не будем играть в шаш.. т.е. в шахматы.

--
Regards, LVT.



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2006.07.23;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.51 MB
Время: 0.014 c
2-1151943068
Vudu
2006-07-03 20:11
2006.07.23
Печать нескольких страниц


2-1151850216
Yaro
2006-07-02 18:23
2006.07.23
вызвать property класса-родителя


15-1150810602
Cerberus
2006-06-20 17:36
2006.07.23
Как заблокировать входящий трафик


1-1149670151
Creative_ltd
2006-06-07 12:49
2006.07.23
загрузка картинки из DLL


6-1142432663
www111
2006-03-15 17:24
2006.07.23
Indy 10 передача и прием данных





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский