Sending Cntrl-C ??

G

gamename

import os
import signal
import subprocess

popen = subprocess(...)
os.kill(popen.pid, signal.SIGINT)

Or with Python 2.6+:

popen.send_signal(signal.SIGINT)

Thanks, Christian. Would that work on win32 as well?

-T
 
C

Christian Heimes

gamename said:
Thanks, Christian. Would that work on win32 as well?

No, Windows doesn't support the same, rich set of signal as Unix OSes.

Christian
 
G

gamename

True but irrelevant to the question.
To the OP: you can download the pywin32 package from sourceforge, and use
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pgid)
or call the same function using ctypes.
Seehttp://msdn.microsoft.com/en-us/library/ms683155(VS.85).aspxfor some
important remarks.

Thanks, guys. Good info.
-T
 
G

gamename

win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pgid)

How do you determine the value of 'pgid'?
 
G

Gabriel Genellina

How do you determine the value of 'pgid'?

Make the child start a new process group, then its pid is the process
group ID. You have to use the "creationflags" parameter of subprocess.open
The documentation for GenerateConsoleCtrlEvent
http://msdn.microsoft.com/en-us/library/ms683155.aspx states that you
can't send CTRL_C_EVENT to another process group, only CTRL_BREAK_EVENT
(and only to the same console as the sender process). A little example:

<code>
import subprocess
import ctypes
import time

CREATE_NEW_PROCESS_GROUP = 512
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT = 1
GenerateConsoleCtrlEvent = ctypes.windll.kernel32.GenerateConsoleCtrlEvent

print "start child process"
p = subprocess.Popen("cmd /c for /L %d in (10,-1,0) do @(echo %d && sleep
1)",
creationflags = CREATE_NEW_PROCESS_GROUP)
print "pid=", p.pid
print "wait 3 secs"
time.sleep(3)
print "send Ctrl-Break"
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p.pid)
print "wait for child to stop"
print "retcode=", p.wait()
print "done"
</code>

Output:

start child process
pid= 872
wait 3 secs
10
9
8
7
send Ctrl-Break
wait for child to stop
retcode= 255
done

(Instead of ctypes and those magical constants, you can install the
pywin32 package and use win32api.GenerateConsoleCtrlEvent,
win32con.CTRL_BREAK_EVENT and win32process.CREATE_NEW_PROCESS_GROUP)

The only way I know of to send a Ctrl-C event to a different console
involves remote code injection.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,132
Latest member
TeresaWcq1
Top