FRI-OS
example/posix/pipes-basic_usage.c

Shows basic usage of anonymous pipes

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main(void)
{
// the pair of file descriptors representing
// both ends of the pipe
int pipe_fds[2];
// the end open for reading is at index 0
const int read_end = 0;
// the end open for writing is at index 1
const int write_end = 1;
// try to create a new anonymous pipe
if(pipe(pipe_fds) < 0)
{
// complain on error and exit
perror("Error creating pipe");
return 1;
}
// write a test string into the end of the pipe
// that is open for writing
const char* input = "This is a test input string";
write(pipe_fds[write_end], input, strlen(input)+1);
// read input into a buffer from the end of the pipe
// that is open for reading
char buffer[256];
read(pipe_fds[read_end], buffer, sizeof(buffer)/sizeof(buffer[0]));
// print the read string
printf("Read '%s' from the pipe\n", buffer);
// input and the contents of the buffer should be the same
assert(strcmp(input, buffer) == 0);
return 0;
}