Created
June 20, 2022 08:49
-
-
Save kflu/70f8c21517594b406eab534331ba3667 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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