473,563 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[Windows] Sending CTRL-C event to console application

I have a Windows command line based application that only shuts down
cleanly if it sees "CTRL-C" on the console. I need to automate the
running of this application, but still allow the user sitting at the
machine to cancel the process cleanly if he/she needs to. In Unix this
would be a tiny shell script that used "kill -15", but under Windows
there does not seem to be an easy way to do this, at least that I can
find.

Below is a test program, based on CreateProcess.p y from "Python
Programming on Win32". The
win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid) lines
don't seem to do anything. What they should do is nothing in the case
of notepad, and exit out of the dir builtin process in the case of the
cmd.exe process.

Any ideas on how to make this work?

# CreateProcessDc .py
#
# Demo of creating two processes using the CreateProcess API,
# then waiting for the processes to terminate.

import win32process
import win32event
import win32con
import win32api
import time

# Create a process specified by commandLine, and
# The process' window should be at position rect
# Returns the handle to the new process.
def CreateMyProcess (commandLine, rect):
# Create a STARTUPINFO object
si = win32process.ST ARTUPINFO()
# Set the position in the startup info.
si.dwX, si.dwY, si.dwXSize, si.dwYSize = rect
# And indicate which of the items are valid.
si.dwFlags = win32process.ST ARTF_USEPOSITIO N | \
win32process.ST ARTF_USESIZE
# Set Creation Flags
CreationFlags = win32process.CR EATE_NEW_CONSOL E | \
win32process.CR EATE_NEW_PROCES S_GROUP | \
win32process.NO RMAL_PRIORITY_C LASS
# Rest of startup info is default, so we leave it alone.
# Create the process.
info = win32process.Cr eateProcess(
None, # AppName
commandLine, # Command line
None, # Process Security
None, # ThreadSecurity
0, # Inherit Handles?
CreationFlags,
None, # New environment
None, # Current directory
win32process.ST ARTUPINFO()) # startup info.
##si) # startup info.
# Return the handle to the process.
# Recall info is a tuple of (hProcess, hThread, processId,
threadId)
return (info[0], info[2])

def RunEm():
pids = []
handles = []
# First get the screen size to calculate layout.
screenX = win32api.GetSys temMetrics(win3 2con.SM_CXSCREE N)
screenY = win32api.GetSys temMetrics(win3 2con.SM_CYSCREE N)
# First instance will be on the left hand side of the screen.
rect = 0, 0, screenX/2, screenY
handle, pid = CreateMyProcess ("notepad", rect)
handles.append( handle)
pids.append(pid )
# Second instance of Notepad will be on the right hand side.
rect = screenX/2+1, 0, screenX/2, screenY
cmd2 = "cmd /k dir /s/p c:\\"
handle, pid = CreateMyProcess (cmd2, rect)
handles.append( handle)
pids.append(pid )

# Now we have the processes, wait for them both
# to terminate.
# Rather than waiting the whole time, we loop 10 times,
# waiting for one second each time, printing a message
# each time around the loop
countdown = range(1,10)
countdown.rever se()
for i in countdown:
print "Waiting %d seconds for apps to close" % i
rc = win32event.Wait ForMultipleObje cts(
handles, # Objects to wait for.
1, # Wait for them all
1000) # timeout in milli-seconds.
if rc == win32event.WAIT _OBJECT_0:
# Our processes closed!
print "Our processes closed in time."
break
# else just continue around the loop.
else:
# We didn't break out of the for loop!
print "Giving up waiting - sending CTRL-C to processes"
for pid in pids:
try:
print "Sending CTRL-C to process with pid: " +
str(pid)

win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid)

win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid)

win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid)

win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid)

win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid)
except win32api.error:
pass
print "Waiting 10 seconds, then going to terminate processes"
time.sleep(10)
print "Giving up waiting - killing processes"
for handle in handles:
try:
win32process.Te rminateProcess( handle, 0)
except win32process.er ror:
# This one may have already stopped.
pass

if __name__=='__ma in__':
RunEm()

Feb 8 '07 #1
3 9658
En Thu, 08 Feb 2007 15:54:05 -0300, Daniel Clark <dj******@gmail .com>
escribió:
I have a Windows command line based application that only shuts down
cleanly if it sees "CTRL-C" on the console. I need to automate the
running of this application, but still allow the user sitting at the
machine to cancel the process cleanly if he/she needs to. In Unix this
would be a tiny shell script that used "kill -15", but under Windows
there does not seem to be an easy way to do this, at least that I can
find.

Below is a test program, based on CreateProcess.p y from "Python
Programming on Win32". The
win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid) lines
don't seem to do anything. What they should do is nothing in the case
of notepad, and exit out of the dir builtin process in the case of the
cmd.exe process.

Any ideas on how to make this work?
From your process creation code:
CreationFlags = win32process.CR EATE_NEW_CONSOL E | \
win32process.CR EATE_NEW_PROCES S_GROUP | \
win32process.NO RMAL_PRIORITY_C LASS
From http://msdn2.microsoft.com/en-us/library/ms683155.aspx
"Only those processes in the group that share the same console as the
calling process receive the signal. In other words, if a process in the
group creates a new console, that process does not receive the signal, nor
do its descendants."

Maybe you have better luck on a Windows programming group, asking how to
send a Ctrl-C event (or a SIGINT signal) to another process attached to a
different console.

--
Gabriel Genellina

Feb 9 '07 #2
On Feb 8, 9:12 pm, "Gabriel Genellina" <gagsl...@yahoo .com.arwrote:
En Thu, 08 Feb 2007 15:54:05 -0300, Daniel Clark <djbcl...@gmail .com>
escribió:
I have a Windows command line based application that only shuts down
cleanly if it sees "CTRL-C" on the console. I need to automate the
running of this application, but still allow the user sitting at the
machine to cancel the process cleanly if he/she needs to. In Unix this
would be a tiny shell script that used "kill -15", but under Windows
there does not seem to be an easy way to do this, at least that I can
find.
Below is a test program, based on CreateProcess.p y from "Python
Programming on Win32". The
win32api.Genera teConsoleCtrlEv ent(win32con.CT RL_C_EVENT, pid) lines
don't seem to do anything. What they should do is nothing in the case
of notepad, and exit out of the dir builtin process in the case of the
cmd.exe process.
Any ideas on how to make this work?

From your process creation code:
CreationFlags = win32process.CR EATE_NEW_CONSOL E | \
win32process.CR EATE_NEW_PROCES S_GROUP | \
win32process.NO RMAL_PRIORITY_C LASS

Fromhttp://msdn2.microsoft .com/en-us/library/ms683155.aspx
"Only those processes in the group that share the same console asthe
calling process receive the signal. In other words, if a process in the
group creates a new console, that process does not receive the signal, nor
do its descendants."
Thanks, although I'm 99% sure I've also tried it without
CREATE_NEW_CONS OLE (with a process that should just die if sent CTRL-
C, so it was monitorable via Task Manager) and it still didn't work.

I'm going to try taking a different approach by using a GUI Automation
tool like WATSUP [1] or pywinauto[2] next.
Maybe you have better luck on a Windows programming group, asking how to
send a Ctrl-C event (or a SIGINT signal) to another process attached to a
different console.
>From what I've found via Google [3], Windows has no real concept of
signals, and no equivalent to SIGINT.

[1] WATSUP - Windows Application Test System Using Python
http://www.tizmoi.net/watsup/intro.html

[2] pywinauto - Python Win32 Automation
http://www.openqa.org/pywinauto/

[3] how to send a SIGINT to a Python process?
http://mail.python.org/pipermail/pyt...er/343461.html

Feb 9 '07 #3
On Feb 9, 9:12 am, "Daniel Clark" <djbcl...@gmail .comwrote:
I'm going to try taking a different approach by using a GUI Automation
tool like WATSUP [1] or pywinauto[2] next.
This works:

AutoIT [1] code (compiled to an executable):
Run(@ComSpec & ' /k ' & $CmdLineRaw )
This was necessary because other means of starting cmd.exe didn't
actually spawn a new window. Syntax is just like:
C:\autoitrun.ex e "cd c:\Program Files\Tivoli\TS M & dir /s/p"
And that will pop up a new cmd.exe window with a dir /s/p listing of
cd c:\Program Files\Tivoli\TS M

Python code (changes service to be able to interact with desktop and
then runs the above):

import win32service
import os, sys

def EnsureInteracti veService(servi cename):
scm = win32service.Op enSCManager(Non e, None,
win32service.SC _MANAGER_ALL_AC CESS)
try:
svc = win32service.Op enService(scm, servicename,
win32service.SC _MANAGER_ALL_AC CESS)
except:
print '''Error: Couldn't open service with name "''' +
servicename + '''"'''
sys.exit(1)
oldsvccfg = win32service.Qu eryServiceConfi g(svc)
win32service.Ch angeServiceConf ig(svc, # scHandle
oldsvccfg[0] |
win32service.SE RVICE_INTERACTI VE_PROCESS, # serviceType
oldsvccfg[1], # startType
oldsvccfg[2], # errorControl
oldsvccfg[3], # binaryFile
oldsvccfg[4], # loadOrderGroup
oldsvccfg[5], # bFetchTag
oldsvccfg[6], # serviceDeps
oldsvccfg[7], # acctName
'', # password
oldsvccfg[8]) # displayName
win32service.Cl oseServiceHandl e(svc)
win32service.Cl oseServiceHandl e(scm)

EnsureInteracti veService("TSM for WPLC")
os.chdir("c:\\P rogram Files\\WPLC-TSM\\updates")
os.system("auto itrun.exe dir /s/p")

[1] AutoIt v3 - Automate and Script Windows Tasks
http://www.autoitscript.com/autoit3/

Feb 9 '07 #4

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

Similar topics

4
7854
by: Per Magnus L?vold | last post by:
Hi, I am working with a simple Java program which communicates over the serial port with a GSM modem. Using Hypertermial, I can send messages and need to press control-z to process the messages. I have created a PrintStream over the serial port, but I do not know how to send control-z from the program! I fin in another Google- thread that...
4
13951
by: Scott | last post by:
I am using a TCPIP connection to communicate over port 23 (telnet) to a server, and I am having to mimic normal command line interface you owuld see in a telnet session (i.e. I have to write to this socket just like you would enter things on the keyboard if you telneted to this server). In a normal telnet session you can enter some commands...
3
3136
by: Mark | last post by:
Any Visual C++ source code available for disabling the following keys in windows 2000. Alt + Ctrl + Del Ctrl + Esc Windows Key to Remove task bar Function keys (or Alt + Function keys or Ctrl + function keys) disabling the Right mouse
1
3446
by: Alfredo Barrientos | last post by:
Hi, I have a little trouble trying to assign a Toolbar control to another toolbar variable control. I am getting my forms controls with this: for (int j = 0; j <= frmChild.Controls.Count - 1; j++) { // Some operations
3
11374
by: s99999999s2003 | last post by:
hi i have a program that works very similar to tail -f in Unix It will need a Ctrl-C in order to break out of the program. I wish to run this program using python (either thru os.system() or some other subprocess modules) and how can i pass Ctrl-C to this program to terminate it in python? thanks
2
8627
by: s99999999s2003 | last post by:
hi i have a program that works very similar to tail -f in Unix It will need a Ctrl-C in order to break out of the program. I wish to run this program using python (either thru os.system() or some other subprocess modules) and how can i pass Ctrl-C to this program to terminate it in python? thanks
1
10461
by: Vlad Dogaru | last post by:
Hello, I've written a simple, standalone wiki server in Python. It runs a BaseHTTPServer's serve_forever() method until a KeyboardInterrupt is caught, at which point it writes changes to a file and exits. This works as expected in Linux. However, in Windows I cannot stop the script with Control-C. I've only been able to stop it with...
6
17768
by: =?Utf-8?B?TWljaGFlbCAwMw==?= | last post by:
I need to disable the clipboard function in Windows XP. We are having a problem with users using CTRL+C in one program, then using CTRL+V in another. Specifically, they type their password into notepad, copy it to the clipboard, then paste it in another program. The other program runs on Windows XP. Obviously, the correct answer is to have...
1
1463
rhitam30111985
by: rhitam30111985 | last post by:
Hi all .. i am trying to do something really weird ... here is my code : import os os.system("mail -s test xxx@gmail.com asdaskdjkasdaasdad")
4
1858
by: Propad | last post by:
Hello, I know this issue pops up once in a while, but I haven't found a good answer to it. I need to debug a long running application under windows. The application is a combined java/python framework for testing ECUs in the automotive industry. Basically, the Java GUI (Eclipse-based) starts test-cases written in Python and provides the...
0
7664
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...
0
7885
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. ...
1
7638
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7948
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...
0
6250
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...
1
5484
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.