×

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data through a shared memory buffer. In C++, you can use the pipe function to create a pipe and the read and write functions to send and receive data through the pipe.

Syntax

The syntax for using pipes in C++:

1. Creating a pipe:

int fd[2];
if (pipe(fd) == -1) {
std::cerr<< "Error: pipe creation failed" << std::endl;
    return 1;
}

The pipe function is used to create a pipe. It takes a single argument, a pointer to an array of two integers. The first element of the array is used to read from the pipe, and the second element is used to write to the pipe. If the function returns -1, the pipe creation has failed.

2. Writing to a pipe:

std::string message = "Hello from the parent process!";
if (write(fd[1], message.c_str(), message.length()) == -1) {
std::cerr<< "Error: write to pipe failed" << std::endl;
    return 1;
}

The write function is used to write data to a file descriptor, in this case the write end of the pipe represented by fd[1]. It takes three arguments: the file descriptor to write to, a pointer to the data, and the number of bytes to be written.

3. Reading from a pipe:

char buffer[256];
if (read(fd[0], buffer, sizeof(buffer)) == -1) {
std::cerr<< "Error: read from pipe failed" << std::endl;
    return 1;
}

The read function is used to read data from a file descriptor, in this case, the read end of the pipe represented by fd[0]. It takes three arguments: the file descriptor to read from, a pointer to the buffer where the data will be stored, and the number of bytes to be read.

4. Closing a pipe:

close(fd[0]);  // close the read end of the pipe
close(fd[1]);  // close the write end of the pipe

The close function is used to close a file descriptor. It takes a single argument, the file descriptor, to be closed.

It is important to remember that pipe read and write are blocked by default. So if there is nothing to read or write, it will block the program.

#include <unistd.h>
#include <iostream>
#include <string>
int main() {
    int fd[2];  // file descriptor for the pipe
pid_tpid;  // process ID


    // create the pipe
    if (pipe(fd) == -1) {
std::cerr<< "Error: pipe creation failed" << std::endl;
        return 1;  }
pid = fork();  // create a new process
    if (pid< 0) {  // fork failed
std::cerr<< "Error: fork failed" << std::endl;
        return 1;
    } else if (pid> 0) {  // parent process
        close(fd[0]);  // close the read end of the pipe
std::string message = "Hello from the parent process!";
        // write the message to the pipe
        if (write(fd[1], message.c_str(), message.length()) == -1) {
std::cerr<< "Error: write to pipe failed" << std::endl;
            return 1;  }
        close(fd[1]);  // close the write end of the pipe
    } else {  // child process
        close(fd[1]);  // close the write end of the pipe
        char buffer[256];
        // read the message from the pipe
        if (read(fd[0], buffer, sizeof(buffer)) == -1) {
std::cerr<< "Error: read from pipe failed" << std::endl;
            return 1;   }
std::cout<< "Received message: " << buffer << std::endl;
        close(fd[0]);  // close the read end of the pipe
    }
    return 0;
}

In the above example:

The pipe function is created, and the file descriptor for the pipe is stored in the fd array.

The fork function is used to create a new process, and the ID of the new process is stored in the pid variable.

The parent process writes a message to the pipe using the write function, and the child reads the message from the pipe using the read function.

It will output "Received message: Hello from the parent process!".

Please note that this is just a one-way pipethat can be used and can also be implemented within a single process. It is important to note that the pipe only works between related processes. Also, Pipes have a limited buffer size, so if too much data is written to the pipe, the writing process will be blocked until there is more room in the buffer.In addition to pipes, there are other mechanisms for IPC in a Unix-like system, such as shared memory, message queues, and sockets.


Related Topics

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.