Skip to content

Instantly share code, notes, and snippets.

@kflu
Created June 20, 2022 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kflu/70f8c21517594b406eab534331ba3667 to your computer and use it in GitHub Desktop.
Save kflu/70f8c21517594b406eab534331ba3667 to your computer and use it in GitHub Desktop.
/*
* Reliably write data to named pipe, udp style.
*
* Compile:
* cc npcat.c -o npcat
*
* Test npcat without reader:
* mkfifo kk
* dd if=/dev/random bs=1k count=1k | npcat kk 2>/dev/null
*
* Test npcat with reader:
* mkfifo kk
* cat <>kk &
* dd if=/dev/random bs=1k count=1k | npcat kk 2>/dev/null
*/
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
void print_usage() {
fprintf(stderr, "prog <fname>\n");
}
int main(int argc, char** argv) {
if (argc < 2) {
print_usage();
return 1;
}
const char* fname = argv[1];
signal(SIGPIPE, SIG_IGN);
const int NBUF = 1024;
void* buf = malloc(NBUF);
while (1) {
int fdout = open(fname, O_WRONLY | O_NONBLOCK);
while (1) {
int n = read(0, buf, NBUF);
if (!n) {
return 0;
}
if (write(fdout, buf, n) < 0) {
fprintf(stderr, "err: %d\n", errno);
close(fdout);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment