4

I have a console application in Mono under Linux that uses Console.CancelKeyPress to listen for SIGINT. However, this applications refuses to run in the background, as it always immediately gets stopped.

Here's a reduced example:

using System;
using System.Threading;

static class Program
{
    static void Main()
    {
        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
        Console.WriteLine("Sleeping");
        Thread.Sleep(100000);
        Console.WriteLine("Done");
    }

    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        Console.WriteLine("In handler.");
    }
}

If I try to run this application in the background under bash, this is the result:

~/test$ mono test.exe &
[1] 4516
~/test$

[1]+  Stopped                 mono test.exe
~/test$

I had to hit enter again to see the "stopped" message, but it happens immediately. As you can see, it never reaches the Console.WriteLine call.

If I try to send SIGINT using kill (which should end the process because the handler doesn't set e.Cancel to true), nothing happens until I resume the process using fg, at which point it ends immediately (it never enters the handler).

If I start the process in the foreground, then interrupt it with ctrl-z and use bg, it again gets stopped immediately, only this time if I send SIGINT and then resume it with fg, the handler does get invoked.

If I remove the Console.CancelKeyPress event handler assignment, the process runs in the background just fine.

I'm using Mono 2.10.8 and Debian 6.0.2.

If all else fails, I can replicate the functionality I need using Mono.Unix.UnixSignal, but if someone has a solution for this I'd definitely like to hear it.

UPDATE: It seems there's another problem with Console.CancelKeyPress for my purposes. I will run my process using nohup so the input is not a console but /dev/null. In this situation, Mono will never trigger the CancelKeyPress event, even if you send SIGINT using kill. UnixSignal it is, then.

Sven
  • 21,903
  • 4
  • 56
  • 63

0 Answers0