Skip to content

stdout is not flushed using custom main

According to the using your own main() guide, Prepare two files.

main.c:

#include <stdio.h>
#include "HsFFI.h"

#ifdef __GLASGOW_HASKELL__
#include "Vomit_stub.h"
#endif

int main(int argc, char *argv[])
{
    int i;

    hs_init(&argc, &argv);

    vomit();

    hs_exit();
    return 0;
}

Vomit.hs:

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}

module Vomit where

import Data.ByteString
import Data.ByteString.Char8 ()
import Prelude hiding (putStr)

foreign export ccall vomit :: IO ()
vomit = putStr "Wrrreerrerek\n"

Compile the code:

$ ghc -c Vomit.hs
$ ghc --make -no-hs-main -optc-O main.c Vomit -o main

Run:

$ ./main
Wrrreerrerek
$

Looks fine. However:

$ ./main > output.txt
$ cat output.txt
$

output.txt is empty.

It seems when the output is done by some Haskell code called by a C code, and the stdout is redirected to a file, the output is not properly flushed. Changing Vomit.hs to:

{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}

module Vomit where

import Data.ByteString
import Data.ByteString.Char8 ()
import Prelude hiding (putStr)

import System.IO (hFlush, stdout)

foreign export ccall vomit :: IO ()
vomit = putStr "Wrrreerrerek\n" >> hFlush stdout

which manually flushes stdout, fixes the behavior.

Since hs_exit() on the C side is supposed to terminate the RTS and flush all output, this seems to be a bug.

Tested with GHC 7.0.4 on Debian GNU/Linux for x86.

Trac metadata
Trac field Value
Version 7.0.4
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information