How to Create a Named Pipe

How to Create a Named Pipe thumbnail
Inter-process communication using named pipes allows for fluid coding.

A powerful feature of Linux, along with other varieties of Unix, is the ability for one command to provide the input to another command using a pipe. Represented on the keyboard as the vertical bar "|", pipes allow separate programs to talk to each other without being developed to do so. In this manner, pipes serve as an inherent method of Inter Process Communication, or IPC. Pipes may also be used explicitly to enable processes to communicate. To facilitate processes identifying the pipe created for use, it is convenient to assign the pipe a predictable name that a process may open for reading or writing. Follow these steps to name a pipe.

Things You'll Need

  • C/C++ compiler
  • Text editor
Show More

Instructions

    • 1

      Launch a text editor and open a C/C++ source file.

    • 2

      Create one end of a pipe using the libc mkfifo API in the form int mkfifo(const char *pathname, mode_t mode); For example, mkfifo("/tmp/mypipe", 0666);.

    • 3

      Check the return value of the mkfifo API to ensure that it is equal to zero, as this indicates success. Note that if the return value is not zero, the error may not be fatal. To determine if the pipe is viable, check the value of errno. If errno is equal to EEXIST, then the pipe already exists and the program may continue.

    • 4

      Establish the direction of communication and invoke the libc open API specifying the name of the pipe assigned in Step 2 as well as the mode, read or write. For example: open("/tmp/mypipe", 0_RDONLY);. Note that a pipe may only be opened by a given process as either readable or writable, but not both. If the current program will read from the pipe, then repeat Steps 1 through 4 in another program to create the process that will write to the pipe.

    • 5

      Open a command terminal and perform a long listing on the "/tmp" directory. Note the presence of the file "mypipe" and the leading attribute is set as "p," to indicate that it is the proper type of pipe. If the sample process choses to open the pipe as readable, use the echo command on the command line to redirect information to the pipe for use by the process. For example, if you type "echo Hello > /tmp/mypipe" it will be available to the process when you press the Enter key.

Related Searches:

References

Resources

  • Photo Credit John Foxx/Stockbyte/Getty Images

Comments

You May Also Like

Related Ads

Featured