Tag: Linux

Using the Screen command

Screen command benefits

  • Can be used to launch multiple shells from a single SSH session.
  • Detach and re-attach from multiple ssh session.
  • Running process which can take more time and need session to be kept alive.
  • To keep the session alive without any network disruptions.

The command to create a screen session is

screen -t <screen name> -S <socket file name>

To detach a screen session

ctrl+a + d

To list the screen sessions

screen -ls

To reattach the screen session

screen -r <pid/name from the list>

Presume you lost the console where the screen was running before detaching the screen. You can detach and reattach using the below command

screen -dr <pid/name from the list>

Single instance in Linux applications

Sometimes you may need to write an application in lnux for which multiple instances are not allowed. There is a simple way to achieve even though you have lot of other ways like semaphores, sockets etc to achieve the same. Here is a small snippet code to achieve the same using file locking.

#include <sys/file.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

 

int pid_file = -1; int rc = -1;

pid_file = open(“/var/run/whatever.pid”, O_CREAT | O_RDWR, 0666);

rc = flock(pid_file, LOCK_EX | LOCK_NB);

if(rc) {

if(EWOULDBLOCK == errno)     {

close(pid_file); // another instance is running

return;

}

}

else {

// this is the first instance

}