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

Not able to run interactive program using C# Process class

Hi Friends,

The basic issue is "To read stdin and stdout in the same program" The following program is i have wrote using thread but i figured out that stdout is working but it is not working when application need the input.

'myprog.pl' is the simple perlscript which ask for the your name and print the same. the execution sequence is given below:

c:\ myprog.pl
Enter your name: Myname
Your name is: Myname

When i am running this script from my C# prog given below it it is not asking for the name at all and it is giving following output;

C:\myCSharpProg.exe
stdin
stdout
Enter your name:Your name is :

Could anyone please help me on this, it will be veryhelpful to me if any alternative method is there to achieve this.

Thanks in Advanced,
Megha


Expand|Select|Wrap|Line Numbers
  1. public void ProgramExecute(
  2. string password,
  3. string commandPath,
  4. string commandArguments)
  5. process = new Process(); 
  6. process.StartInfo.FileName = "cmd.exe";
  7. process.StartInfo.Arguments = " /c \"" +  " myprog.pl";
  8. process.StartInfo.RedirectStandardError = true; 
  9. process.StartInfo.RedirectStandardInput = true; 
  10. process.StartInfo.RedirectStandardOutput = true; 
  11. process.StartInfo.Verb = "Open"; 
  12. process.StartInfo.UseShellExecute = false;
  13. process.StartInfo.ErrorDialog = false;
  14. process.StartInfo.CreateNoWindow = true;
  15. process.StartInfo.LoadUserProfile = true;
  16. // get the domain and user name parts of the current
  17. // windows identity
  18. Match identity_match = Regex.Match(
  19. WindowsIdentity.GetCurrent().Name,
  20. @"^([^\\]+)\\(.+)$");
  21. // domain name
  22. string dn = identity_match.Groups[1].Value;
  23. // user name
  24. string un = identity_match.Groups[2].Value;
  25. // only set the domain if it is an actual domain and
  26. // not the name of the local machine, i.e. a local account
  27. // invoking sudo
  28. if (!Regex.IsMatch(dn,
  29. Environment.MachineName, RegexOptions.IgnoreCase))
  30. {
  31. process.StartInfo.Domain = dn;
  32. }
  33. process.StartInfo.UserName = un;
  34. // transform the plain-text password into a
  35. // SecureString so that the ProcessStartInfo class
  36. // can use it 
  37. process.StartInfo.Password = new System.Security.SecureString();
  38.  
  39. for (int x = 0; x < password.Length; ++x)
  40. process.StartInfo.Password.AppendChar(password[x]);
  41. process.Start(); 
  42. new Thread(new ThreadStart(this.readStdin)).Start(); 
  43. new Thread(new ThreadStart(this.readStdout)).Start(); 
  44. process.WaitForExit(); 
  45. Environment.Exit(process.ExitCode); 
  46. private void readStdin()
  47. {
  48. try
  49. {
  50. Console.WriteLine("stdin");
  51. string line;
  52. while ((line = Console.In.ReadLine()) != null)
  53. {
  54. process.StandardInput.WriteLine(line);
  55. }
  56. }
  57. catch (Exception e)
  58. {
  59. Console.Error.WriteLine(e.Message);
  60. }
  61. private void readStdout()
  62. {
  63. try
  64. {
  65. Console.WriteLine("stdout");
  66. int b;
  67. while ((b = process.StandardOutput.BaseStream.ReadByte()) != -1)
  68. {
  69. Console.Write((char)b);
  70. }
  71. }
  72. catch (Exception e)
  73. {
  74. Console.Error.WriteLine(e.Message);
  75. }
  76.  
  77. }
Apr 8 '08 #1
14 10757
Plater
7,872 Expert 4TB
You do a lot of wierd stuff.

For instance
Expand|Select|Wrap|Line Numbers
  1. process.StartInfo.FileName = "cmd.exe";
  2. process.StartInfo.Arguments = " /c \"" +  " myprog.pl";
  3.  
Could be written as
Expand|Select|Wrap|Line Numbers
  1. process.StartInfo.FileName = "myprog.pl";
  2. process.StartInfo.Arguments = "";
  3.  

You are using readline and writeline, is it possible you are getting extra newline characters in there?
Apr 8 '08 #2
Thanks for the reply.

But i cant change "cmd.exe" because i wants to all the commands with extensions (.msc,.pl,.cpl,.exe etc) which may not be win32 application where Process class failed to spawn process when it assigned Process.File. About "\n" i am taking care.

Thanks,
Paresh
Apr 8 '08 #3
Plater
7,872 Expert 4TB
If CMD can be run with the arguments provided, the arguments provided will run by themselves as the processes.
By using CMD with arguments, you are effectively just re-wrapping the application.
It's the same as if you just ran CMD
Then in the CMD window type your filename.

The only things that don't work like that are commands like "dir", "cd" and other console specific commands.
Apr 8 '08 #4
Hi,

I am running inputreader.exe which is interactive program using C# program given below:

Followin is my C# program which redirect standard output and input.

private void mainProcess(
string password,
string commandPath,
string commandArguments)
{
ProcessStartInfo psi = new ProcessStartInfo(@"c:\temp\inputreader.exe");
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process proc = Process.Start(psi);
StreamReader reader = proc.StandardOutput;
string line = "";
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
proc.StandardInput.WriteLine(line);
}
}

following is the inputreader.exe sourcecode.

static void Main(string[] args)
{
try
{
Console.WriteLine("Login[]");
Console.ReadLine();
Console.WriteLine("\r\nPassword[]:");
Console.ReadLine();
Console.WriteLine("\r\nDo you wish to continue? y/n");
string answer = Console.ReadLine();
if (answer.Equals("y"))
Console.WriteLine("yippie");
else
Console.WriteLine("aborting");
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
}

Here C# program is not waiting while inputreader.exe needs the output and its simply proceeding and just printing the output as follow:

C:\>MyCSharpProg.exe
Login[]

Password[]:

Do you wish to continue? y/n
aborting

Could anyone please help me here.

Thanks,
Paresh
Apr 8 '08 #5
You are absolutely right that Shell commands will not run.I am checking for all this commands internally in my application and showing error messages if user has specified one of these command.

The actuall process will be argument to cmd command that also i agree with you. But to run all the extensions commands/files i has to use "cmd.exe /c" else its not possible to run all those commands.

Here i am able to read standard output but not standard input to get the input from user. Could you tell me why it is like this? or any alternative method will be very helpful to me.

Thanks,
Paresh
Apr 8 '08 #6
(truncating for double post)
Apr 8 '08 #7
Plater
7,872 Expert 4TB
EDIT: Please don't double post, I merged the threads.
MODERATOR

I just ran that program and it is running just fine?
I should point out:
Console.WriteLine(line);
proc.StandardInput.WriteLine(line);
You are already writing something back to the input, so it's not like it's "not waiting", its that you are already writing data.


Here is what I used for handling the redirecting:
Expand|Select|Wrap|Line Numbers
  1. private static Process proc;
  2.         private static void mainProcess(string password,string commandPath,string commandArguments)
  3.         {
  4.             ProcessStartInfo psi = new ProcessStartInfo(@"c:\inputreader.exe");
  5.             psi.RedirectStandardOutput = true;
  6.             psi.RedirectStandardInput = true;
  7.             psi.UseShellExecute = false;
  8.             psi.CreateNoWindow = true;
  9.             proc = Process.Start(psi);
  10.             new Thread(new ThreadStart(ShowProcStdOut)).Start();
  11.             new Thread(new ThreadStart(GiveProcStdIn)).Start(); 
  12.         }
  13.         private static void GiveProcStdIn()
  14.         {
  15.             string line = "";
  16.             try
  17.             {
  18.                 StreamReader reader = new StreamReader(Console.OpenStandardInput());// proc.StandardOutput;
  19.                 while (!reader.EndOfStream)
  20.                 {
  21.                     line = reader.ReadLine();
  22.                     proc.StandardInput.WriteLine(line); 
  23.                 }
  24.             }
  25.             catch (Exception e)
  26.             {
  27.                 Console.Error.WriteLine("GiveProcStdIn:" + e.Message);
  28.             }
  29.         }
  30.         private static void ShowProcStdOut()
  31.         {
  32.             string line = "";
  33.             try
  34.             {
  35.                 StreamReader reader = proc.StandardOutput; 
  36.                 while (!reader.EndOfStream)
  37.                 {
  38.                     line = reader.ReadLine();
  39.                     Console.WriteLine(line);
  40.                 }
  41.             }
  42.             catch (Exception e)
  43.             {
  44.                 Console.Error.WriteLine("ShowProcStdOut:"+e.Message);
  45.             }
  46.         } 
  47.  
Apr 8 '08 #8
Sorry for that..I will take of that next time...

Simply great ....It is working fine for me. But when i run it, even the process inputreader is ended, it is not getting terminated and i have to press cntr-c to exit. I think that is because of " while (!reader.EndOfStream)" condition is stdin thread.

Thanks a lot, You have taken me out from a great trouble.
Paresh
Apr 9 '08 #9
Another problem with my implementation:

I used your suggested solution and it works great when My application directly calling the "inputreader.exe".

Now consider the following scenario:

Assume there are following C# programs:
1. Client.exe
2. Server.exe
3. GetToken.exe
4. MainProcess.exe

Here Client.exe invokes the function in Server.exe and in turns this Server.exe calls GetToken.exe by generating new process using Process class. Again this GetToken.exe calls MainProcess.exe same way. And at last this MainProcess.exe is running and this is the process which is responsible to execute "inputreader.exe" using code given by you. Here it is showing only black cmd window and not showing any output and also not asking for any inputs.

Much complicated...!!! Here i think problem is we lost the standard I/O handle and dont know where it is redirected.

Let me know if you have any questions here. Could you please help me here.

Thanks,
Paresh
Apr 9 '08 #10
Ahhh... The solution is not working for the perl script. :( :(

I tried to run following simple 'interactive.pl' perl script though your code:

print"Enter your name:\n";
$name = <STDIN>;
print"Your name is : $name\n";

C# program Working:
------------------------------
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe" , @"c:\temp\inputreader\inputreader\bin\Release\inpu treader.exe");
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
proc = Process.Start(psi);
new Thread(new ThreadStart(ShowProcStdOut)).Start();
new Thread(new ThreadStart(GiveProcStdIn)).Start();


C# Program Not Working:
------------------------------------
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", @"/c c:\local\interactive.pl");
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
proc = Process.Start(psi);
new Thread(new ThreadStart(ShowProcStdOut)).Start();
new Thread(new ThreadStart(GiveProcStdIn)).Start();

Any thoughts??? I think I am giving you much troubles.

Thanks,
Paresh
Apr 9 '08 #11
Sorry..I haven't appended output when I ran perl script from C# program.

Output:
---------
Enter your name: //It should wait here to get the input but not waiting
Your name is :

Thanks,
Paresh
Apr 9 '08 #12
Hey Plater,

Congratulations on your 4000 posts passes.

Could you please help me on this thread alone. It is very difficult and important for me.

Thanks,
Paresh
Apr 9 '08 #13
Plater
7,872 Expert 4TB
I am unsure why perl does not deal well with the redirection of stdio. Perhaps you could check with the Perl people?
Apr 9 '08 #14
Ok..thats fine...Anything about #10 update ??? Any idea will be very helpful to me.

Thanks,
Paresh
Apr 9 '08 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

20
by: Joe | last post by:
When you run "python -i scriptname.py" after the script completes you left at the interactive command prompt. Is there a way to have this occur from a running program? In other words can I...
8
by: Peter A. Schott | last post by:
Per subject - I realize I can copy/paste a line at a time into an interactive session when I'm trying to debug, but was wondering if there is any tool out there that allows me to copy sections of...
22
by: SeeBelow | last post by:
Is there any way, in C, of interacting with a running program, but still using code that is portable, at least between linux and Windows? By "interacting" it could be something as simple as...
5
by: Stephan Steiner | last post by:
Hi I'm trying to write a program that interacts with an interactive cli program, that is a program that does some processing but every now and then requires some user input. My problem is that...
1
by: Nick Palmer | last post by:
As the title suggests, I've got a question about running an ASP.NET app on a server that has no interactive desktop login. In all our testing of our app here,the server always had an interactive...
4
by: Eric | last post by:
Hello, I need to allow a web page to launch an interactive program on the web server. For this example, I'd like to have the ASP.NET open notepad on the asp server, so the current logged-in...
2
by: WJ | last post by:
I have three ASPX pages: 1. "WebForm1.aspx" is interactive, responsible for calling a web site (https://www.payMe.com) with $$$. It is working fine. 2. "WebForm2.aspx" is non-interactive, a...
20
by: Xavoux | last post by:
Hello all... I can't remind which function to use for safe inputs... gets, fgets, scanf leads to buffer overflow... i compiled that code with gcc version 2.95.2, on windows 2000 char tmp0 =...
2
by: Matimus | last post by:
On Apr 11, 2:32 am, Evan <xdi...@gmail.comwrote: Do you want a custom shell that does whatever you want? Or do you want an interactive python shell that has some custom commands? For the first...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.