Tag Archives: c example

Named Pipes in C

If you happen to be programming in C at some point and you want to pass messages between two processes named pipes is an option. What you are doing is defining a node on the filesystem as a FIFO node and then piping messages through it. In the examples below I create a reader which reads from a named pipe. The pipe is defined as DEFAULT_PIPE in test.h. The writer application will write out a single line to named pipe.

//
// test.h
//

#ifndef test_h
#define test_h

#define DEFAULT_PIPE "/Users/nick/pipetest"

#endif
//
//  NamedPipeReader
//

#include
#include
#include
#include
#include
#include "test.h"

int main(void)
{
    FILE *fp;
    char readbuf[128];

    // Try creating pipe if it doesn't exit.
    mknod(DEFAULT_PIPE, S_IFIFO|0666, 0);

    // Lets say what is going on.
    fprintf(stdout, "Pipe %s created!\n", DEFAULT_PIPE);
    while(1)
    {
        // Open the named pipe.
        fp = fopen(DEFAULT_PIPE, "r");
        if (fp == NULL)
        {
            // Print error if an issue shows up.
            perror("fopen error");
            exit(1);
        }

        // Get string from the pipe.
        fgets(readbuf, 128, fp);
        // Print the pipe data to stdout (console).
        fprintf(stdout, "Received string: %s\n", readbuf);
        // Close the named pipe.
        fclose(fp);
    }

    return(0);
}
//
//  NamedPipeWriter
//

#include
#include
#include "test.h"

int main(int argc, char *argv[])
{
    FILE
        *pipe;
    char
        buffer[128];

    // Open existing pipe.
    if((pipe = fopen(DEFAULT_PIPE, "w")) == NULL) {
        perror("error from fopen");
        exit(1);
    }

    // Read a line from stdin (console).
    fgets(buffer, sizeof(buffer), stdin);

    // Write the line to the pipe.
    fputs(buffer, pipe);

    // Close the pipe.
    fclose(pipe);
    return(0);
}
Advertisement