Last active
April 16, 2024 14:02
-
-
Save ikegami/f862662d78e92c05e81033765b9d0175 to your computer and use it in GitHub Desktop.
This file contains 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
#include <err.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
int main( void ) { | |
int pipefds[2]; | |
if ( pipe( pipefds ) == -1 ) | |
err( 1, "pipe" ); | |
pid_t pid = fork(); | |
if ( pid == -1 ) | |
err( 1, "fork" ); | |
if ( pid == 0 ) { | |
close( pipefds[ 0 ] ); | |
FILE *fh = fdopen( pipefds[ 1 ], "w" ); | |
if ( fh == NULL) | |
err( 1, "fdopen" ); | |
for ( unsigned i=1; i<=1000; ++i ) { | |
if ( fprintf( fh, "This is line %u\n", i ) < 0 ) | |
err( 1, "fprintf" ); | |
} | |
if ( fclose( fh ) == EOF ) | |
err( 1, "fclose" ); | |
exit( 0 ); | |
} | |
close( pipefds[ 1 ] ); | |
int newfd = dup( pipefds[ 0 ] ); | |
if ( newfd == -1 ) | |
err( 1, "dup" ); | |
{ | |
FILE *fh = fdopen( pipefds[ 0 ], "r" ); | |
if ( fh == NULL ) | |
err( 1, "fdopen" ); | |
char *line = NULL; | |
size_t n = 0; | |
for ( unsigned i = 5; i--; ) { | |
ssize_t bytes_read = getline( &line, &n, fh ); | |
if ( bytes_read == -1 ) | |
err( 1, "getline" ); | |
if ( bytes_read == 0 ) | |
errx( 1, "Unexpected EOF" ); | |
if ( line[ bytes_read-1 ] == '\n' ) | |
line[ bytes_read-1 ] = 0; | |
printf( "<%s>\n", line ); | |
} | |
if ( fclose( fh ) == EOF ) | |
err( 1, "fclose" ); | |
free( line ); | |
} | |
printf( "Should follow with \"This is line 6\" if there's no data loss:\n" ); | |
{ | |
char s[ 31 ]; | |
ssize_t bytes_read = read( newfd, s, 30 ); | |
if ( bytes_read == -1 ) | |
err( 1, "read" ); | |
s[ bytes_read ] = 0; | |
printf( "[%s]\n", s ); | |
} | |
} | |
/* **************************************** | |
Output: | |
god | |
<This is line 1> | |
<This is line 2> | |
<This is line 3> | |
<This is line 4> | |
<This is line 5> | |
Should follow with "This is line 6" if there's no data loss: | |
[is line 248 <--- Lines 6 to 247 are lost, as well as the start of line 248. | |
This is line 249 | |
T] | |
**************************************** */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment