Sunday, December 3, 2023

How to identify process is listening to FIFO (Handle brocken pipe issues)

 In my previous post about named pipes, I mentioned that, "there has to be a reading process "attached" for the other side of the pipe. If you try to open pipe for writing and there is no reading process, open will hang waiting for it"

But there can be issues if reading process is killed/ternminated after attching to FIFO. In that case there will  not be any listner on the other end and writing process would give "Broken pipe" error.

In that case you could use command lsof


e.g. lsof /tmp/myfifo 
Output: 
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME 
wr 64769 isurusa 3w FIFO 202,3 0t0 67668074 /tmp/myfifo 
rd 64781 isurusa 3r FIFO 202,3 0t0 67668074 /tmp/myfifo 

Obove output can be processed and make sure there is a propper listner attched to FIFO.

Below is some C++ code snipet for that.


Using named pipes (FIFO) to inter process communication (IPC) in c++

 Named pipes can be used, if you need to setup a bidirectional channel between two processes.

Traditional UNIX pipe is unnamed and it lasts only during the process lifetime, where as named pipes last as long as the system is up, beyond the life of the process.

A named pipe is basically a file and converted into a FIFO using mkfifo(). 

Then processes attach to it for reading/writing purpose. After that reading and writing can be done as on a regular file in C++.

There have to be reading process "attached" for the other side of the pipe. If you try to open pipe for writing and there is no reading process, open will hang waiting for it or return -1 with errno set to ENXIO (when O_NONBLOCK flag is used)




NOTE:

Pipes are byte-oriented, not message oriented. If you want messages, there's other IPC for that (e.g., SysV message queues).

Since it is a stream of bytes we may need to establish a minimal transport protocol (for example use '\0' byte as a delimiter, Number of bytes write/read form sender/reciever)




Thursday, November 30, 2023

Difference between 'struct' and 'typedef struct' in C++

 

In C++ there is a subtle difference between.
struct Foo { ... };
and
typedef struct { ... } Foo;

In C++ there are few types of identifiers. 
  • Constants 
  • Variables 
  • Functions 
  • Labels 
  • Defined data types 

 These identifiers are stored in different namesapces. If someone write following, he would get an compiler error.
 
struct Foo { ... }; Foo x;

That is because Foo is stored only in namespace for defined data types. 
So, everytime you need to declare an object of Foo, you need to write struct Foo x;

But with following code Foo will be defined in namesapce for variables .
 
struct Foo { ... };
typedef struct Foo Foo;

In short, It can be written as follows.
 
typedef struct Foo { ... } Foo;

So with typedef we can create objects with Foo x;
So we dont have to use struct Foo x; pattern every time we create an object of Foo.

Difference of strcpy and stpcpy in c++

The main difference is the return value of stpcpy.

stpcpy returns the pointer to the terminating \0 character of the target string. This immediately makes clear the purpose of stpcpy and the rationale behind its existence: this function is intended to be used as an intelligent replacement to strcat function in situations when you need to concatenate multiple sub-strings into one string. 
strcat works pretty poorly in such application. The problem with strcat is that it rescans the destination string every time you add something to it, thus doing lots of unnecessary work and basically generating more heat than light. For example, the following code suffers from that problem


const char *part1, *part2, *part3, *part4;
... 
char buffer[size]; /* assume that `size` is calculated properly */ 

strcpy(buffer, part1); 
strcat(buffer, part2); 
strcat(buffer, part3); 
strcat(buffer, part4);

This code can be reimplemented in a much more reasonable way by using stpcpy stpcpy(stpcpy(stpcpy(stpcpy(buffer, part1), part2), part3), part4); 

And if you don't like chained calls, you can use an intermediate pointer to store the return value of intermediate stpcpy calls
 
char *end = buffer; 
end = stpcpy(end, part1); 
end = stpcpy(end, part2); 
end = stpcpy(end, part3); 
end = stpcpy(end, part4);


Of course it is worth mentioning that strcpy and strcat are standard functions, while stpcpy is not. Refrerence : SOF

Wednesday, November 15, 2023

Handling large data sets with C++ STL vectors

 Vectors in C++ standard templat library is an dynamic container which dynamicaly allocate memory as size is increased.When  we deal with a larger data set, freaquent dynamic allocations can reduce the performance of our program.

By using the reserve() function judiciously, we can preallocate memory, reducing the need for frequent reallocations as elements are added. This not only minimizes the overhead associated with dynamic resizing but also enhances contiguous memory allocation, which can have positive effects on cache locality and iteration performance.

Let's consider an example where we have a vector that will be populated with a significant number of elements, but we also need fast random access to these elements. In such a scenario, we might strike a balance by allocating a slightly larger initial capacity than the expected dataset size using reserve(). This reduces the frequency of reallocations, optimizing memory usage.

However, it's crucial to be aware that this approach comes with a trade-off. Allocating more memory than strictly necessary increases the initial memory footprint, and if memory is a critical constraint, we might need to explore alternative solutions. 

In summary, the key is to carefully assess the specific requirements of the application and strike a balance between minimizing memory usage and optimizing for access patterns based on the characteristics of the dataset.

Basic C++ interview questions for beginners


Check if you can answer following basic questions.

1. Explain the difference between deep copy and shallow copy in C++.

2. What is a constructor, and how does it differ from a destructor in C++?

3. What is the purpose of the `virtual` keyword in C++?

4. Explain the difference between `new` and `malloc()` in C++.

5. What is a smart pointer in C++? How does it differ from a raw pointer?

6. Explain the concept of operator overloading in C++

Friday, July 23, 2021

Split a string by a given delimiter

 I was really amazed to find out that C++ string class has no split method. There are plenty of accasions I needed to split a string by a given delimiter. Lets see how to split a string and put substrings in a to vector. 

If you think incrementing varable start is ugly, you can use function find_first_not_of for it

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...