开发者

How redirect StandardInput on Process without process immediately exiting?

开发者 https://www.devze.com 2023-04-04 03:50 出处:网络
I created a utility to lock files lockfile.exe, which accepts two parameters: fileName (file to be locked) and fileShare (share to be applied). I then call this utility from within another application

I created a utility to lock files lockfile.exe, which accepts two parameters: fileName (file to be locked) and fileShare (share to be applied). I then call this utility from within another application to test error conditions when processing locked files. The lockfile.exe utility locks a file with the specified share and then waits for any character input to release the lock and exit.

In my test application I created a class FileLocker with two methods LockFile and UnlockFile as follows:

public class FileLocker
{
    private Process process;

    public void LockFile(string fileName)
    {
        this.process = new Process();
        this.process.StartInfo.RedirectStandardInput = true;
        this.process.StartInfo.UseShellExecute = false;
        this.process.StartInfo.CreateNoWindow = true;
        this.process.StartInfo.FileName = "lockfile.exe";
        this.process.StartInfo.Arguments =
            "\"" + fileName + "\" " + FileShare.Read.ToString();
        this.process.Start();
    }

    public void UnlockFile()
    {
        this.process.StandardInput.Write('X');
        this.process.StandardInput.Flush();
        this.process.WaitForExit();
        this.process.Close();
    }
}

When I call the method LockFile the process immediately exits after starting. It does not wait for the input in UnlockFile. When I do not redirect the standard input, then the process waits for keyboard input.

What do I need to change/fix, so that the process does not immediately exit. I need it to wait for the input p开发者_JAVA技巧rovided in UnlockFile and only then should the process exit?

Update:

Updated to show FileLocker class above and to provide sample calls below:

class Program
{
    static void Main(string[] args)
    {
        FileLocker locker = new FileLocker();
        locker.LockFile("HelloWorld.txt");
        locker.UnlockFile();
    }
}


The problem is likely that you are using Console.ReadKey() in your lockfile.exe application. This does not accept input from standard input but uses low-level keyboard hooks to check for key presses which you cannot send from another application.

I tested your program with a LockFile.exe that just contained a simple Console.ReadLine(), and it works just as expected if I change the Write('X') call to a WriteLine("X") (since the call to readline needs a newline before returning). So I'm suspecting your problem is in the lockfile.exe program rather than this one. Ensure you are using Console.ReadLine() to wait for input from standard input in your lockfile.exe application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号