473,385 Members | 1,843 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

[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.py from "Python
Programming on Win32". The
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_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.STARTUPINFO()
# 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.STARTF_USEPOSITION | \
win32process.STARTF_USESIZE
# Set Creation Flags
CreationFlags = win32process.CREATE_NEW_CONSOLE | \
win32process.CREATE_NEW_PROCESS_GROUP | \
win32process.NORMAL_PRIORITY_CLASS
# Rest of startup info is default, so we leave it alone.
# Create the process.
info = win32process.CreateProcess(
None, # AppName
commandLine, # Command line
None, # Process Security
None, # ThreadSecurity
0, # Inherit Handles?
CreationFlags,
None, # New environment
None, # Current directory
win32process.STARTUPINFO()) # 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.GetSystemMetrics(win32con.SM_CXSCREEN)
screenY = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
# 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.reverse()
for i in countdown:
print "Waiting %d seconds for apps to close" % i
rc = win32event.WaitForMultipleObjects(
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.GenerateConsoleCtrlEvent(win32con.CTRL_C_ EVENT, pid)

win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_ EVENT, pid)

win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_ EVENT, pid)

win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_ EVENT, pid)

win32api.GenerateConsoleCtrlEvent(win32con.CTRL_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.TerminateProcess(handle, 0)
except win32process.error:
# This one may have already stopped.
pass

if __name__=='__main__':
RunEm()

Feb 8 '07 #1
3 9606
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.py from "Python
Programming on Win32". The
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_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.CREATE_NEW_CONSOLE | \
win32process.CREATE_NEW_PROCESS_GROUP | \
win32process.NORMAL_PRIORITY_CLASS
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.py from "Python
Programming on Win32". The
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_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.CREATE_NEW_CONSOLE | \
win32process.CREATE_NEW_PROCESS_GROUP | \
win32process.NORMAL_PRIORITY_CLASS

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_CONSOLE (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.exe "cd c:\Program Files\Tivoli\TSM & 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\TSM

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

import win32service
import os, sys

def EnsureInteractiveService(servicename):
scm = win32service.OpenSCManager(None, None,
win32service.SC_MANAGER_ALL_ACCESS)
try:
svc = win32service.OpenService(scm, servicename,
win32service.SC_MANAGER_ALL_ACCESS)
except:
print '''Error: Couldn't open service with name "''' +
servicename + '''"'''
sys.exit(1)
oldsvccfg = win32service.QueryServiceConfig(svc)
win32service.ChangeServiceConfig(svc, # scHandle
oldsvccfg[0] |
win32service.SERVICE_INTERACTIVE_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.CloseServiceHandle(svc)
win32service.CloseServiceHandle(scm)

EnsureInteractiveService("TSM for WPLC")
os.chdir("c:\\Program Files\\WPLC-TSM\\updates")
os.system("autoitrun.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
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....
4
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...
3
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...
1
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 -...
3
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...
2
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...
1
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...
6
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...
1
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
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.