473,396 Members | 2,147 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,396 software developers and data experts.

Writing Control Characters to Standard Input of a Command-Shell Pr

I am attempting to use a third party command-line utility (WinDump.exe) to
capture network traffic for perfromance analysis. This utility when launched
captures network traffic until Ctrl-C is entered from the keyboard. I launch
this utility (through a batch file) programmatically in a command-shell
process through the Process object with no window (i.e.
myProcess.StartInfo.CreateNoWindow = true). I have re-directed the
StandardInput to a StreamWriter and I need to send a Ctrl-C to this process
through the StreamWriter. Could anyone tell me how to do this?

Thank you much!
--
Mark M
Aug 1 '06 #1
5 5544
Mark M <Ma***@newsgroups.nospamwrote:
I am attempting to use a third party command-line utility (WinDump.exe) to
capture network traffic for perfromance analysis. This utility when launched
captures network traffic until Ctrl-C is entered from the keyboard. I launch
this utility (through a batch file) programmatically in a command-shell
process through the Process object with no window (i.e.
myProcess.StartInfo.CreateNoWindow = true). I have re-directed the
StandardInput to a StreamWriter and I need to send a Ctrl-C to this process
through the StreamWriter. Could anyone tell me how to do this?
The Win32 API function 'GenerateConsoleCtrlEvent()' is what you're
looking for.

-- Barry

--
http://barrkel.blogspot.com/
Aug 1 '06 #2
Hi Mark,

Thanks for your post!

Barry points out the correct API. However, the solution to your problem is
much complex than I expected. GenerateConsoleCtrlEvent Win32 API has a
special limitation. From MSDN:
"Only those processes in the group that share the same console as the
calling process receive the signal."

While .Net Process class internally encapsulate CreateProcess Win32 API, if
you use windbg to set a breakpoint on KERNEL32!CreateProcessW, you will see
that the dwCreationFlags parameter is passed with 0x4000410 from .Net
Process class, which included CREATE_NEW_CONSOLE(0x10) flag. So the new
lauched process will be openned in a new console window, which does not
meet the GenerateConsoleCtrlEvent API requirement.

So if you use GenerateConsoleCtrlEvent API with Process class, you will
have no lucky.

The only way is p/invoke win32 CreateProcess API manually, and do not
specify CREATE_NEW_CONSOLE(0x10) flag. Then the new lauched process will
share the same console as the calling process.

I have written a little sample project to demonstrate this:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Text;

namespace consoletest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
[DllImport("Kernel32.dll")]
public static extern bool GenerateConsoleCtrlEvent(int dwCtrlEvent, int
dwProcessGroupId);

[StructLayout(LayoutKind.Sequential)]
internal class STARTUPINFO
{
public int cb;
public IntPtr lpReserved;
public IntPtr lpDesktop;
public IntPtr lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}

[StructLayout(LayoutKind.Sequential)]
internal class PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool CreateProcess(string lpApplicationName, string
lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool
bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string
lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION
lpProcessInformation);
[STAThread]
static void Main(string[] args)
{
STARTUPINFO si =new STARTUPINFO();
si.cb=Marshal.SizeOf(si);
PROCESS_INFORMATION pi=new PROCESS_INFORMATION();
string szCmdLine="ping msjeff1 -t";
Console.WriteLine("Press any key to lauch the process \nand press again
to generate the Ctrl+C signal");
Console.ReadLine();
// Spawn the other processes as part of this Process Group
bool f = CreateProcess(null, szCmdLine, IntPtr.Zero, IntPtr.Zero, true,
0, IntPtr.Zero, null, si, pi);

Console.ReadLine();
bool fResult=GenerateConsoleCtrlEvent(0, 0);
if(!fResult)
{
Console.WriteLine("GenerateConsoleCtrlEvent failed with error
"+Marshal.GetLastWin32Error());
}
Console.ReadLine();
}
}
}

I ignored this limitation at first and wasted a lot of time in test :-(

Further more, there is another issue: since the WinDump.exe is lauched
invisible, you can not simply tell the lauch console application when to
exit by pressing any key. To resolve this problem, you need another
application to controll the stub console application that lauches the
WinDump.exe and use some inter-process communication to tell it to exit
with GenerateConsoleCtrlEvent. You may use .Net Remoting as the IPC
technology or any native Win32 technologies.

Jeffrey Richter has written an article targeting the above problems, you
may give it a good reading:
http://www.microsoft.com/msj/0698/win320698.aspx

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 1 '06 #3
Thanks, Barry and Jeffrey.

I attempted implementing your solution, Jeffrey, and I am now able to
receive the Ctrl-C in the process running WinDump. However, I still seem to
have two other problems that I have not yet successfully resolved.

1) When the Ctrl-C has been received in the process, WinDump correctly
exits, but since it was launched from a batch file, I get the "Terminate
Batch Process (Y/N)" message and although I attempt to send a "y" to the
console, it doesn't close the window. To get around this, I am calling the
content of the batch file (single line) in my application, but this is not
desirable.

2) I would prefer to have this process run invisibly. Currently it displays
in a command window. Is there a way to hide this? I attempted to create a
"parent" command shell process and call your code within it, but then the
process stopped receiving the Ctrl-C again.

Thanks again for your help.
--
Mark M
""Jeffrey Tan[MSFT]"" wrote:
Hi Mark,

Thanks for your post!

Barry points out the correct API. However, the solution to your problem is
much complex than I expected. GenerateConsoleCtrlEvent Win32 API has a
special limitation. From MSDN:
"Only those processes in the group that share the same console as the
calling process receive the signal."

While .Net Process class internally encapsulate CreateProcess Win32 API, if
you use windbg to set a breakpoint on KERNEL32!CreateProcessW, you will see
that the dwCreationFlags parameter is passed with 0x4000410 from .Net
Process class, which included CREATE_NEW_CONSOLE(0x10) flag. So the new
lauched process will be openned in a new console window, which does not
meet the GenerateConsoleCtrlEvent API requirement.

So if you use GenerateConsoleCtrlEvent API with Process class, you will
have no lucky.

The only way is p/invoke win32 CreateProcess API manually, and do not
specify CREATE_NEW_CONSOLE(0x10) flag. Then the new lauched process will
share the same console as the calling process.

I have written a little sample project to demonstrate this:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Text;

namespace consoletest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
[DllImport("Kernel32.dll")]
public static extern bool GenerateConsoleCtrlEvent(int dwCtrlEvent, int
dwProcessGroupId);

[StructLayout(LayoutKind.Sequential)]
internal class STARTUPINFO
{
public int cb;
public IntPtr lpReserved;
public IntPtr lpDesktop;
public IntPtr lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}

[StructLayout(LayoutKind.Sequential)]
internal class PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool CreateProcess(string lpApplicationName, string
lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool
bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string
lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION
lpProcessInformation);
[STAThread]
static void Main(string[] args)
{
STARTUPINFO si =new STARTUPINFO();
si.cb=Marshal.SizeOf(si);
PROCESS_INFORMATION pi=new PROCESS_INFORMATION();
string szCmdLine="ping msjeff1 -t";
Console.WriteLine("Press any key to lauch the process \nand press again
to generate the Ctrl+C signal");
Console.ReadLine();
// Spawn the other processes as part of this Process Group
bool f = CreateProcess(null, szCmdLine, IntPtr.Zero, IntPtr.Zero, true,
0, IntPtr.Zero, null, si, pi);

Console.ReadLine();
bool fResult=GenerateConsoleCtrlEvent(0, 0);
if(!fResult)
{
Console.WriteLine("GenerateConsoleCtrlEvent failed with error
"+Marshal.GetLastWin32Error());
}
Console.ReadLine();
}
}
}

I ignored this limitation at first and wasted a lot of time in test :-(

Further more, there is another issue: since the WinDump.exe is lauched
invisible, you can not simply tell the lauch console application when to
exit by pressing any key. To resolve this problem, you need another
application to controll the stub console application that lauches the
WinDump.exe and use some inter-process communication to tell it to exit
with GenerateConsoleCtrlEvent. You may use .Net Remoting as the IPC
technology or any native Win32 technologies.

Jeffrey Richter has written an article targeting the above problems, you
may give it a good reading:
http://www.microsoft.com/msj/0698/win320698.aspx

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 2 '06 #4
Hi Mark,

Thanks for your feedback!

Yes, I can reproduce your second problem. CreateNoWindow property is
implemented as passing CREATE_NO_WINDOW flag to the CreateProcess API.
Based on the test, if we pass this flag to the console application,
GenerateConsoleCtrlEvent will not close this console application at all.

Based on my research, because the hidden console application does not share
the same console as our calling console application,
GenerateConsoleCtrlEvent will not try to generate Ctrl+C to the hidden
console application. I think this is by design.

I do not think there is a good workaround regarding this issue. Maybe you
should try to kill the hidden console application as a workaround for
Ctrl+C? Anyway, this is not a good design, I think you may have to give
your design a second thought.

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 3 '06 #5
Hi Mark,

Have you reviewed my last reply? If you have any concern or need any help,
please feel free to tell me, thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 7 '06 #6

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

Similar topics

3
by: Bill Cohagan | last post by:
I'm writing a console app (in C#) and I want to be able to redirect the standard input/output streams when it's run at a command prompt. IOW I want to support the "<" and ">" redirection syntax....
8
by: Peter O'Reilly | last post by:
I have an HTML form with a textarea input box. When the user conducts a post request (e.g. clicks the submit button), an HTML preview page is presented to them with the information they have...
1
by: Fred Nelson | last post by:
Hi: I'm writing an error handling system for my vb.net windows application. I have an error trapping routine that is catching all unexpected errors, writing an entry in an sql database and...
3
by: Frank Niessink | last post by:
Hi list, First of all, I wish you all a happy 2006. I have a small question that googling didn't turn up an answer for. So hopefully you'll be kind enough to send me in the right direction. ...
11
by: Ron L | last post by:
I have a barcode scanner which uses a "keyboard wedge" program so that the data it scans comes through as if it was typed on a keyboard. I am trying to have the data in the barcode be displayed in...
2
by: db2learner | last post by:
Hi, I am new to DB2 and i just started worked on it a couple of days back. I have created basic EMPLOYEE table from control centre which has 2 fields: EmpNo, EmpName. I am trying to write...
7
by: wannymahoots | last post by:
optparse seems to be escaping control characters that I pass as arguments on the command line. Is this a bug? Am I missing something? Can this be prevented, or worked around? This behaviour...
27
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
I have a fully-portable C program (or at least I think I do). It works fine on Windows, but malfunctions on Linux. I suspect that there's something I don't know about the standard input stream...
0
by: AliAmjad | last post by:
Hello All, How can I read from standard input and write to standard output. System.Diagnostics.Process.StandardInput's MSDN reference didn't help as it separately starts the process and then...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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...
0
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,...
0
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,...
0
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...

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.