Skip to content

Instantly share code, notes, and snippets.

@itarato
Created June 3, 2023 15:23
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 itarato/3884a9f471d4ac1ac4cccbab848cfdea to your computer and use it in GitHub Desktop.
Save itarato/3884a9f471d4ac1ac4cccbab848cfdea to your computer and use it in GitHub Desktop.
Demonstrating a Posix pipe writer being full and not being emptied
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#define PIPE_MAX (1 << 16)
int main() {
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("Pipe cannot be acquired");
exit(EXIT_FAILURE);
}
int flags = fcntl(pipefd[1], F_GETFL, 0);
if (flags == -1) {
perror("File flags cannot be obtained");
exit(EXIT_FAILURE);
}
if (fcntl(pipefd[1], F_SETFL, flags | O_NONBLOCK) == -1) {
perror("File flags cannot be set");
exit(EXIT_FAILURE);
}
char buffer[PIPE_MAX + 1];
memset(buffer, 'x', PIPE_MAX + 1);
int write_res = write(pipefd[1], buffer, PIPE_MAX + 1);
printf("Written %d out of %d\n", write_res, PIPE_MAX + 1);
// -> Written 65536 out of 65537
int read_res = read(pipefd[0], buffer, 16);
printf("Read %d\n", read_res);
// -> Read 16
int write_new_res = write(pipefd[1], buffer, 8);
printf("Written %d out of %d\n", write_new_res, 8);
// -> Written -1 out of 8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment