~fhusson

Dotnet Core console exit code compatibility problem

With an old .NET console app, after the migration to .NET Core, we had a strange behavior when running it under an alpine docker image. We used -1 and -2 exit code !

TL;DR : Only use exit code between 0 and 255 if you need linux compatibility because of the POSIX.

How to reproduce the problem

Here is a test console app in C#.

using System;

namespace ExitCode
{
    class Program
    {
        static int Main(string[] args)
        {
            return int.Parse(args[0]);
        }
    }
}

Under Windows Powershell :

dotnet run -1 ; echo $LASTEXITCODE
-1

dotnet run -2 ; echo $LASTEXITCODE
-2

dotnet run 512 ; echo $LASTEXITCODE
512

Under Ubuntu WSL (or linux in general) :

dotnet run -1; echo $?
255

dotnet run -2; echo $?
254

dotnet run 512; echo $?
0

Why the difference

Linux is POSIX

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, [CX] [Option Start] or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.

It manage only 8 bits … 0 to 255 :)

Source found via this comment on stackoverflow

Windows is not POSIX and support the full 32 bits return. More information on this stackoverflow thread

Discuss on Twitter