Pipes & FIFOs

Libraries Required

1#include <unistd.h>
2#include <sys/stat.h>

pipe()

Creates a unidirectional data channel (pipe) using a pair of file descriptors for reading and writing

1int pipe(int pipefd[2]);

Return Value:

  • Success: 0
  • Error: -1

Example:

 1int fd[2];
 2pipe(fd);
 3if (fork() == 0) {
 4    close(fd[0]);
 5    write(fd[1], "Hello", 5);
 6    _exit(0);
 7} else {
 8    close(fd[1]);
 9    char buf[6] = {0};
10    read(fd[0], buf, 5);
11    printf("Parent read: %s\n", buf);
12}

mkfifo()

Creates a named pipe (FIFO) special file that can be used for inter-process communication

1int mkfifo(const char *pathname, mode_t mode);

Return Value:

  • Success: 0
  • Error: -1

Modes:

OctalSymbolicDescription
0400r– — —Read by owner
0200-w- — —Write by owner
0600rw- — —Read/Write by owner
0040— r– —Read by group
0020— -w- —Write by group
0060— rw- —Read/Write by group
0004— — r–Read by others
0002— — -w-Write by others
0006— — rw-Read/Write by others
0666rw- rw- rw-Read/Write by all (owner/group/others)
0644rw- r– r–Owner RW, Group R, Others R

Tip

  • Owner: The user who created the file and has primary control over it
  • Group: Set of different users
  • Others: Users neither owner nor group

Example:

1mkfifo("mypipe", 0666);
2int fd = open("mypipe", O_WRONLY);
3write(fd, "Hi", 2);
Last updated on