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.
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.
PennRobotics|4 years ago
What worked for me initially was the POSIX write() function:
-----As someone else commented, fflush() gives the desired error response.
-----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
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
jwilk|4 years ago
(And silently returning non-zero would be bad anyway.)