Tuesday, September 8, 2020

How to use inotify() in C++

below is a simple C++ code that demonstrates the use of inotify. just copy pasta it into a file and compile using gcc...

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main( )
{
  int length, i = 0;
  int fd;
  int wd;
  char buffer[EVENT_BUF_LEN];

  /*creating the INOTIFY instance*/
  fd = inotify_init();

  /*checking for error*/
  if ( fd < 0 ) {
    perror( "inotify_init" );
  }

  /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
  wd = inotify_add_watch( fd, "/tmp", IN_CREATE | IN_DELETE );

  /*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/ 

  length = read( fd, buffer, EVENT_BUF_LEN ); 

  /*checking for error*/
  if ( length < 0 ) {
    perror( "read" );
  }  

  /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
  while ( i < length ) {     struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];     if ( event->len ) {
      if ( event->mask & IN_CREATE ) {
        if ( event->mask & IN_ISDIR ) {
          printf( "New directory %s created.\n", event->name );
        }
        else {
          printf( "New file %s created.\n", event->name );
        }
      }
      else if ( event->mask & IN_DELETE ) {
        if ( event->mask & IN_ISDIR ) {
          printf( "Directory %s deleted.\n", event->name );
        }
        else {
          printf( "File %s deleted.\n", event->name );
        }
      }
    }
    i += EVENT_SIZE + event->len;
  }
  /*removing the “/tmp” directory from the watch list.*/
   inotify_rm_watch( fd, wd );

  /*closing the INOTIFY instance*/
   close( fd );

Tuesday, March 12, 2019

Reading a Text File Line by Line using Shell Script

Open a text file for reading where $1 is the command argument for the file:

#!/bin/bash
while read line; do
    echo "$line"
done < $1

If you want to skip empty lines...

#!/bin/bash
while read line; do
if [ ! -z "$line" ]; then
echo "$line"
fi
done < $1

if you want to skip lines starting with '#'...

#!/bin/bash
while read line; do
if [ ! -z "$line" ]; then
if [[ ! "$line" == \#* ]]; then
echo "$line"
fi
done < $1

if line has <field> <value> pair separated by ':' e.g. name:john, do this:

while read line; do
if [ ! -z "$line" ]; then
if [[ ! "$line" == \#* ]]; then
left=${line%:*}
echo "$left"
right=${line#*:}
echo "$right"
fi
fi 
done < $1

where 'left' is <field> and 'right' is <value>



Thursday, November 1, 2018

Compiling C++ Codes into shared Library and Linking Them


Compiling C++ Codes into shared library and linking them

Let's say you have files print.h and print.cpp, shown below that contains C++ codes you wish to compile as .so (shared object) file and they are stored in ~/demo/lib folder.

#ifndef __PRINT__
#define __PRINT__

#include <iostream>
#include <stdio.h>
void print(const char* p, bool endl = true);

#endif
#include <print.h>

void print(const char* p, bool endl)
{
std::cout << "print: " << p;
if (endl) std::cout << std::endl;
}

You can compile the above code into .o (static library) file with the command

~/demo/g++ -o lib.o -c ./lib/print.cpp

But we want to compile it as .so (shared library) file so we use the command instead

~/demo/g++ -o ./lib/liblib.so -shared -fpic ./lib/print.cpp

Note that with the above commands, liblib.so and lib.o is created in ~/demo/lib folder upon successful compilation.

Now let's say you have another set of C++ files loop.cpp and loop.h, shown below and you wish to compile them together with another C++ file into an .so file...

#ifndef __LOOP__
#define __LOOP__

#include <iostream>
#include <unistd.h>

class loop
{
public:
loop()
{
std::cout << "loop constructor"<< std::endl;
}
virtual ~loop()
{
std::cout << "loop destructor"<< std::endl;
}

void run(int i, int r);
};

#endif

#include <loop.h>

void loop::run(int i, int r)
{
while(r)
{
sleep(i);
std::cout << "loop..." << std::endl;
r--;
}
}

To compile print.cpp and loop.cpp files into a single .so file, do the command as shown below

~/demo/g++ -o ./lib/liblib.so -shared -fpic ./lib/print.cpp ./lib/loop.cpp

Now that we have .so file already, let's create a C++ program that will use this shared library and use the function and class it contains.
The C++ file below will be our C++ program. It is stored as main.cpp in ~/demo folder.
It uses print() from print.cpp to print "hello world" and uses loop class to perform a loop of 5 intervals.

#include <iostream>
#include <print.h>
#include <loop.h>

int main()
{
print("hello world");
loop p;
p.run(1,5);
return 0;
}

Let's compile this code and link the shared library with it. The command below shows how to compile it into "run".

g++ -o run main.cpp -L/lib -llib -I./lib -I./

If compile is successful, and executable named 'run' should appear in ~/demo folder. If you execute it, you might encounter an error as shown below. This is because when executing a program that has dependency on a shared library, it needs to know where the library is.

run: error while loading shared libraries: liblib.so: cannot open shared object file: No such file or directory

To fix this, you can do either of the two possible solutions

1. Copy the liblib.so into any folder listed in the system's LD_LIBRARY_PATH environment variable. This is a more consistent solution because you only do this once.

2. add ~/demo/lib folder into LD_LIBRARY_PATH environment variable. You have to keep setting this every time you try to execute your program in a new terminal. To do this, follow the command below:

~/setenv LD_LIBRARY_PATH ~/demo/lib:${LD_LIBRARY_PATH}

Now try to run the program again.

Using Makefile 

You can create a makefile to simplify this process. Copy the code below into ~/demo/makefile

all: so main

so : ./lib/print.cpp ./lib/loop.cpp
g++ -o ./lib/liblib.so -shared -fpic ./lib/print.cpp ./lib/loop.cpp -I./lib

main : ./lib/liblib.so
g++ -o run main.cpp -L./lib -llib -I./lib -I ./

Then just call 'make' and the whole compiling process will be done.








Thursday, June 21, 2018

Handy Git Commands List

List of various one liner git logs:

git config --global alias.lg "log --oneline --decorate --all --graph -50"

git config --global alias.lg "log --pretty=format:\"%h%x09%ad%x09%s\""

Monday, October 23, 2017

Handling PID's Using Shell Script

How to get process' own PID 
Copy the below command into a bash text file and then execute it.
The PID of this process will be printed.

#!/bin/bash
echo $$



Thursday, June 1, 2017

wxWidgets FAQ's


  • How to install GTK on CentOS
    • >yum groupinstall " Development Tools" (optional)
    • >yum install gtk+-devel gtk2-devel
  • Where to find GTK installation on CentOS
    • /usr/include
  • How to check GTK version installed
    • pkg-config --modversion gtk+-2.0
    • rpm -qa | grep gtk2

Monday, May 1, 2017

Command Line Compilers on Various Platforms and Software Languages


  • Linux (CentOS)
    • gcc -o <output> <source code>
      • gcc -o foo foo.c where foo is executable, and foo.c is the source code