cosmopolitan/examples/ctrlc.c

63 lines
1.9 KiB
C
Raw Normal View History

2020-06-15 14:18:57 +00:00
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/errno.h"
2020-06-15 14:18:57 +00:00
#include "libc/log/check.h"
#include "libc/log/color.internal.h"
2020-06-15 14:18:57 +00:00
#include "libc/log/log.h"
#include "libc/mem/mem.h"
#include "libc/nt/thread.h"
2020-06-15 14:18:57 +00:00
#include "libc/runtime/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/sig.h"
volatile bool gotctrlc;
2020-06-15 14:18:57 +00:00
void GotCtrlC(int sig) {
gotctrlc = true;
2020-06-15 14:18:57 +00:00
}
int main(int argc, char *argv[]) {
ssize_t rc;
size_t got, wrote;
unsigned char buf[512];
fprintf(stderr, "This echos stdio until Ctrl+C is pressed.\n");
CHECK_NE(
-1, sigaction(SIGINT, &(struct sigaction){.sa_handler = GotCtrlC}, NULL));
for (;;) {
rc = read(0, buf, BUFSIZ);
if (rc != -1) {
got = rc;
2020-06-15 14:18:57 +00:00
} else {
CHECK_EQ(EINTR, errno);
break;
2020-06-15 14:18:57 +00:00
}
if (!got) break;
rc = write(1, buf, got);
if (rc != -1) {
wrote = rc;
} else {
CHECK_EQ(EINTR, errno);
break;
}
CHECK_EQ(got, wrote);
}
if (gotctrlc) {
fprintf(stderr, "Got Ctrl+C\n");
} else {
fprintf(stderr, "Got EOF\n");
2020-06-15 14:18:57 +00:00
}
return 0;
2020-06-15 14:18:57 +00:00
}