Showing posts with label Linux Programming. Show all posts
Showing posts with label Linux Programming. Show all posts

Tuesday, December 5, 2023

How to invoke operating system command from a C/C++ program.

There can be situations in where we need to excute a linux commands from a C++ program.

Then system() is the function you need.

It is simple, only the command has to be passed and it will return 0 if command successfuly executed, 1 otherwise.

syntax: int system(const char *command);

As system function is declared in stdlib.h, it can be considered a C function. But in C++, stdlib.h is merged into the std namespace and is located in the cstdlib .

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)




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...