29 December 2011

Disable Control-C [ CTRL+C ] in linux

Signals are the notification send to a process on the occurrence of an event.

#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

struct sigaction act;

void sighandler(int signum, siginfo_t *info, void *ptr)
{
    printf("Received signal %d\n", signum);
    printf("Signal originates from process %lu\n",
        (unsigned long)info->si_pid);
}

int main()
{
    printf("I am %lu\n", (unsigned long)getpid());

    memset(&act, 0, sizeof(act));
#if 0
    act.sa_sigaction = sighandler;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGINT, &act, NULL);
#endif
#if 0
    act.sa_handler = SIG_IGN;
    sigaction(SIGINT, &act, NULL);
#endif

    signal(SIGINT, SIG_IGN);

    // Waiting for CTRL+C...
    sleep(100);

    return 0;
}

Reference:
http://nixcraft.com/shell-scripting/12605-shell-script-disable-ctrl-c-ctrl-z.html

How to handle SIGSEGV, but also generate a core dump

Signals are the notification send to a process on the occurrence of an event.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

void sighandler(int signum)
{
    printf("Process %d got signal %d\n", getpid(), signum);
    signal(signum, SIG_DFL);
    kill(getpid(), signum);
}

int main()
{
    signal(SIGSEGV, sighandler);
    printf("Process %d waits for someone to send it SIGSEGV\n",
        getpid());
    sleep(1000);

    return 0;
}
ulimit -c unlimited
echo "0" > /proc/sys/kernel/core_uses_pid
echo "core" > /proc/sys/kernel/core_pattern
$ ls
sigs.c
$ gcc sigs.c
$ ./a.out
Process 2149 waits for someone to send it SIGSEGV
Process 2149 got signal 11
Segmentation fault (core dumped)
$ ls
a.out*  core  sigs.c

Reference:
http://www.alexonlinux.com/signal-handling-in-linux
http://www.alexonlinux.com/how-to-handle-sigsegv-but-also-generate-core-dump
http://aplawrence.com/Linux/limit_core_files.html

28 December 2011

extract file in linux

extract () {
   if [ -f $1 ] ; then
       case $1 in
 *.tar.bz2) tar xvjf $1 && cd $(basename "$1" .tar.bz2) ;;
 *.tar.gz) tar xvzf $1 && cd $(basename "$1" .tar.gz) ;;
 *.tar.xz) tar Jxvf $1 && cd $(basename "$1" .tar.xz) ;;
 *.bz2)  bunzip2 $1 && cd $(basename "$1" /bz2) ;;
 *.rar)  unrar x $1 && cd $(basename "$1" .rar) ;;
 *.gz)  gunzip $1 && cd $(basename "$1" .gz) ;;
 *.tar)  tar xvf $1 && cd $(basename "$1" .tar) ;;
 *.tbz2)  tar xvjf $1 && cd $(basename "$1" .tbz2) ;;
 *.tgz)  tar xvzf $1 && cd $(basename "$1" .tgz) ;;
 *.zip)  unzip $1 && cd $(basename "$1" .zip) ;;
 *.Z)  uncompress $1 && cd $(basename "$1" .Z) ;;
 *.7z)  7z x $1 && cd $(basename "$1" .7z) ;;
 *)  echo "don't know how to extract '$1'..." ;;
       esac
   else
       echo "'$1' is not a valid file!"
   fi
}
http://ubuntuforums.org/showthread.php?t=1116012