top | item 30612184

(no title)

s_ariga | 4 years ago

#include <stdio.h> #include <stdlib.h>

int main(void) { if(puts("Hello, World!")!=EOF) { return EXIT_SUCCESS; }else { return EXIT_FAILURE; } }

discuss

order

PennRobotics|4 years ago

puts() returns 13 with no pipe and with pipe to /dev/full, which I just learned is due to buffering.

What worked for me initially was the POSIX write() function:

  #include <stdlib.h>
  #include <unistd.h>
  
  int main(void)
  {
      int status;
      status = write(1, "Hello World!\n", 13);
      if (status < 0)  { return EXIT_FAILURE; }
      return EXIT_SUCCESS;
  }
-----

As someone else commented, fflush() gives the desired error response.

  #include <stdio.h>
  #include <stdlib.h>
  
  int main(void)
  {
      int status;
      puts("Hello World!");
      status = fflush(stdout);
      if (status < 0)  { return EXIT_FAILURE; }
      return EXIT_SUCCESS;
  }
-----

andreyv probably has the best alternative[1], which is checking fflush() and ferror() at the program's end and calling perror(). It's better because it outputs an actual error message on the current terminal, and you don't need to write a special error checking wrapper.

[1] https://news.ycombinator.com/item?id=30611924

unwind|4 years ago

I tried basically exactly that, and it didn't work for me.

On my test system (Ubuntu 21.10 on x86_64) the puts() call never fails.

I switched to a raw write() and that successfully catches it, by returning -1 when output is redirected to /dev/full.

Quite interesting, actually.

Karellen|4 years ago

puts(), like printf() and all the C-standardised "stdio" functions use buffered writes. So that is also buggy, because the buffer won't be flushed until after main() returns. You need to call and check the return value of "fflush(stdout)" manually to get the correct result.

jwilk|4 years ago

This still succeeds, because puts() is buffered.

(And silently returning non-zero would be bad anyway.)