Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# close standard out

I would like to be able to detach my program from the console much like wget -b. A code fragment might look like

static void Main(string[] args)
{
    var settings = new Settings(args);
    if (settings.Background)
    {
        /*Tell the user what's going on.*/
        System.Console.WriteLine("Detatching from console. The program will still be running.");
        System.Console.Out.Close();
    }
    /*do work then exit.*/
}

But System.Console.Out.Close(); doesn't do the right thing.

To clarify, the "right thing" is, when running this program from the console, the prompt should re-appear. Or, when running this program from explorer.exe, the console window should close.

Please let me know if I am not being clear.

like image 584
lmat - Reinstate Monica Avatar asked Mar 28 '12 17:03

lmat - Reinstate Monica


2 Answers

The source for wget to which you refer is available here. You'll notice that in mswindows.c lines 193 - 314, a fork procedure is implemented. They spawn a new instance of wget and pass it the same parameters.

The comments are informative, too:

Windows doesn't support the fork() call; so we fake it by invoking another copy of Wget with the same arguments with which we were invoked.

And on line 102:

Under Windows 9x, if we were launched from a 16-bit process ... the parent process should resume right away. Under NT ... this is a futile gesture as the parent will wait for us to terminate before resuming.

The short answer seems to be "Don't do that."

like image 133
lmat - Reinstate Monica Avatar answered Oct 13 '22 11:10

lmat - Reinstate Monica


There are 3 channels open for any console app running: STDIN, STDOUT, STDERR. Traditionally all 3 needs to be closed for an app to release the console.

In Windows there does however seem to be an API method for doing so: FreeConsole ... and pinvoke.net.

Edit: Another SO post says it isn't possible without starting a background process: How to make a windowless / command-line application return but continue executing in background? ... In Unix it would be enough with a fork();.

like image 29
Tedd Hansen Avatar answered Oct 13 '22 11:10

Tedd Hansen