EDUCATION

Learning Process

Simple Debug Related of a Bubble Sort Related Written in Ruby


$ruby -rdebug bubblesort.rb 
Debug.rb
Emacs support available.

bubblesort.rb:12:array_size = 300
(rdb:1) break 1
Set breakpoint 1 at bubblesort.rb:1
(rdb:1) next
bubblesort.rb:13:x = 0
(rdb:1) next
bubblesort.rb:14:y = 0
(rdb:1) w
--> #1 bubblesort.rb:14
(rdb:1) l
[9, 18] in bubblesort.rb
   9  =end
   10  
   11  
   12  array_size = 300
   13  x = 0
=> 14  y = 0
   15  z = 0
   16  hold = 0
   17  ran = Array.new(array_size)
   18  
(rdb:1) up
At toplevel
#1 bubblesort.rb:14
(rdb:1) down
At stack bottom
#1 bubblesort.rb:14
(rdb:1) next
bubblesort.rb:15:z = 0
(rdb:1) next
bubblesort.rb:16:hold = 0
(rdb:1) next
bubblesort.rb:17:ran = Array.new(array_size)
(rdb:1) next
bubblesort.rb:19:while x < array_size  
(rdb:1) next
bubblesort.rb:20:    ran[x] = rand(1..1000)
(rdb:1) next
bubblesort.rb:21:    x +=1
(rdb:1) next
bubblesort.rb:20:    ran[x] = rand(1..1000)
(rdb:1) w
--> #1 bubblesort.rb:20
(rdb:1) l
[15, 24] in bubblesort.rb
   15  z = 0
   16  hold = 0
   17  ran = Array.new(array_size)
   18  
   19  while x < array_size  
=> 20      ran[x] = rand(1..1000)
   21      x +=1
   22  end
   23  
   24  x = 0
(rdb:1) trace on
Trace on.
(rdb:1) next
#0:bubblesort.rb:21::-:     x +=1
bubblesort.rb:21:    x +=1
(rdb:1) next
#0:bubblesort.rb:20::-:     ran[x] = rand(1..1000)
bubblesort.rb:20:    ran[x] = rand(1..1000)
(rdb:1) next
#0:bubblesort.rb:21::-:     x +=1
bubblesort.rb:21:    x +=1
(rdb:1) trace off
Trace off.
(rdb:1) next
bubblesort.rb:20:    ran[x] = rand(1..1000)
(rdb:1) next
bubblesort.rb:21:    x +=1
(rdb:1) next
bubblesort.rb:20:    ran[x] = rand(1..1000)
(rdb:1) w
--> #1 bubblesort.rb:20
(rdb:1) f
--> #1 bubblesort.rb:20
(rdb:1) l
[15, 24] in bubblesort.rb
   15  z = 0
   16  hold = 0
   17  ran = Array.new(array_size)
   18  
   19  while x < array_size  
=> 20      ran[x] = rand(1..1000)
   21      x +=1
   22  end
   23  
   24  x = 0
(rdb:1) q
Really quit? (y/n) y
$

Simple Debugging


$gdb bubblesort 
GNU gdb (GDB) 7.6.2 (Debian 7.6.2-1)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later 
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
...
Reading symbols from /home/jeffrin/beautifulwork-sorting/gnu-c/bubblesort...done.
(gdb) break 1
Breakpoint 1 at 0x400508: file bubblesort.c, line 1.
(gdb) r
Starting program: /home/jeffrin/beautifulwork-sorting/gnu-c/bubblesort 
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000
warning: Could not load shared library symbols for linux-vdso.so.1.
Do you need "set solib-search-path" or "set sysroot"?

Breakpoint 1, main () at bubblesort.c:17
17    int array_size=400;
(gdb) next
20    for(x = 0; x < array_size; x++)
(gdb) next
21    ran[x]= rand();
(gdb) print x
$1 = 0
(gdb) next
20    for(x = 0; x < array_size; x++)
(gdb) next
21    ran[x]= rand();
(gdb) print x
$2 = 1
(gdb) array_size=3
Undefined command: "array_size".  Try "help".
(gdb) let array_size=3
Undefined command: "let".  Try "help".
(gdb) set array_size=3
(gdb) next
20    for(x = 0; x < array_size; x++)
(gdb) print x
$3 = 1
(gdb) next
21    ran[x]= rand();
(gdb) print x
$4 = 2
(gdb) next
20    for(x = 0; x < array_size; x++)
(gdb) print x
$5 = 2
(gdb) next
23    for(x = 0; x < array_size; x++) {
(gdb) print x
$6 = 3
(gdb) next
24      for(y = 0; y < array_size; y++) {
(gdb) quit
A debugging session is active.

    Inferior 1 [process 4064] will be killed.

Quit anyway? (y or n) y
$

Stat - Display File or File System Status

GNU Command stat -f /

$stat -f /
  File: "/"
    ID: bc427fdafb7b0541 Namelen: 255     Type: ext2/ext3
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 18864769   Free: 16209639   Available: 15251363
Inodes: Total: 4792320    Free: 4684854
$

Explanation
Display file or file system status.

Related Source Code Exposition

static bool
do_statfs (char const *filename, bool terse, char const *format)
{
  STRUCT_STATVFS statfsbuf;

  if (STATFS (filename, &statfsbuf) != 0)
    {
      error (0, errno, _("cannot read file system information for %s"),
             quote (filename));
      return false;
    }

  if (format == NULL)
    {
      format = (terse
                ? "%n %i %l %t %s %S %b %f %a %c %dn"
                : "  File: "%n"n"
                "    ID: %-8i Namelen: %-7l Type: %Tn"
                "Block size: %-10s Fundamental block size: %Sn"
                "Blocks: Total: %-10b Free: %-10f Available: %an"
                "Inodes: Total: %-10c Free: %dn");
    }

  print_it (format, filename, print_statfs, &statfsbuf);
  return true;
}

Source Code Highlight

Stat the file system and print what we find.


Featured Image
FIXME

Related Knowledge
Due to shell aliases and built-in stat' command, using an unadornedstat’ interactively or in a script may get you different functionality than that described here. Invoke it via env' (i.e., env stat …‘) to avoid interference from the shell.

Tee - Read From Standard Input and Write to Standard Output and Files

GNU Command

$tee name
my name is nice.
my name is nice.
$cat name
my name is nice.
$


Explanation


Copy standard input to each FILE, and also to standard output. A special variant of the tee for the shell is called script and permits duplicating all input commands submitted to a shell into a file.


Related Source Code Exposition

static bool
tee_files (int nfiles, const char **files)
{
  FILE **descriptors;
  char buffer[BUFSIZ];
  ssize_t bytes_read;
  int i;
  bool ok = true;
  char const *mode_string =
    (O_BINARY
     ? (append ? "ab" : "wb")
     : (append ? "a" : "w"));

  descriptors = xnmalloc (nfiles + 1, sizeof *descriptors);

  /* Move all the names `up' one in the argv array to make room for
     the entry for standard output.  This writes into argv[argc].  */
  for (i = nfiles; i >= 1; i--)
    files[i] = files[i - 1];

  if (O_BINARY && ! isatty (STDIN_FILENO))
    xfreopen (NULL, "rb", stdin);
  if (O_BINARY && ! isatty (STDOUT_FILENO))
    xfreopen (NULL, "wb", stdout);

  /* In the array of NFILES + 1 descriptors, make
     the first one correspond to standard output.   */
  descriptors[0] = stdout;
  files[0] = _("standard output");
  setvbuf (stdout, NULL, _IONBF, 0);

  for (i = 1; i <= nfiles; i++)
    {
      descriptors[i] = (STREQ (files[i], "-")
                        ? stdout
                        : fopen (files[i], mode_string));
      if (descriptors[i] == NULL)
        {
          error (0, errno, "%s", files[i]);
          ok = false;
        }
      else
        setvbuf (descriptors[i], NULL, _IONBF, 0);
    }

  while (1)
    {
      bytes_read = read (0, buffer, sizeof buffer);
#ifdef EINTR
      if (bytes_read < 0 && errno == EINTR)
        continue;
#endif
      if (bytes_read <= 0)
        break;

      /* Write to all NFILES + 1 descriptors.
         Standard output is the first one.  */
      for (i = 0; i <= nfiles; i++)
        if (descriptors[i]
            && fwrite (buffer, bytes_read, 1, descriptors[i]) != 1)
          {
            error (0, errno, "%s", files[i]);
            descriptors[i] = NULL;
            ok = false;
          }
    }

  if (bytes_read == -1)
    {
      error (0, errno, _("read error"));
      ok = false;
    }

  /* Close the files, but not standard output.  */
  for (i = 1; i <= nfiles; i++)
    if (!STREQ (files[i], "-")
        && descriptors[i] && fclose (descriptors[i]) != 0)
      {
        error (0, errno, "%s", files[i]);
        ok = false;
      }

  free (descriptors);

  return ok;
}

Source Code Highlight


Copy the standard input into each of the NFILES files in FILES and into the standard output. Return true if successful.

Featured Image
FIXME


Related Knowledge


The `tee’ command copies standard input to standard output and also to any files given as arguments. This is useful when you want not only to send some data down a pipe, but also to save a copy.

Free - Display Amount of Free and Used Memory in the System

GNU command

$free
             total       used       free     shared    buffers     cached
Mem:        507008     432908      74100          0      14700     186816
-/+ buffers/cache:     231392     275616
Swap:      1485972          0    1485972
$free -m
             total       used       free     shared    buffers     cached
Mem:           495        422         72          0         14        182
-/+ buffers/cache:        225        269
Swap:         1451          0       1451
$

Explanation
Display amount of free and used memory in the system.


Related Source Code Exposition
#define S(X) ( ((unsigned long long)(X) << 10) >> shift)

const char help_message[] =
"usage: free [-b|-k|-m|-g] [-l] [-o] [-t] [-s delay] [-c count] [-V]n"
"  -b,-k,-m,-g show output in bytes, KB, MB, or GBn"
"  -l show detailed low and high memory statisticsn"
"  -o use old format (no -/+buffers/cache line)n"
"  -t display total for RAM + swapn"
"  -s update every [delay] secondsn"
"  -c update [count] timesn"
"  -V display version information and exitn"
;

int main(int argc, char *argv[]){
    int i;
    int count = 0;
    int shift = 10;
    int pause_length = 0;
    int show_high = 0;
    int show_total = 0;
    int old_fmt = 0;

    /* check startup flags */
    while( (i = getopt(argc, argv, "bkmglotc:s:V") ) != -1 )
        switch (i) {
        case 'b': shift = 0;  break;
        case 'k': shift = 10; break;
        case 'm': shift = 20; break;
        case 'g': shift = 30; break;
        case 'l': show_high = 1; break;
        case 'o': old_fmt = 1; break;
        case 't': show_total = 1; break;
        case 's': pause_length = 1000000 * atof(optarg); break;
        case 'c': count = strtoul(optarg, NULL, 10); break;
    case 'V': display_version(); exit(0);
        default:
            fwrite(help_message,1,strlen(help_message),stderr);
        return 1;
    }

    do {
        meminfo();
        printf("             total       used       free     shared    buffers     cachedn");
        printf(
            "%-7s %10Lu %10Lu %10Lu %10Lu %10Lu %10Lun", "Mem:",
            S(kb_main_total),
            S(kb_main_used),
            S(kb_main_free),
            S(kb_main_shared),
            S(kb_main_buffers),
            S(kb_main_cached)
        );
        // Print low vs. high information, if the user requested it.
        // Note we check if low_total==0: if so, then this kernel does
        // not export the low and high stats.  Note we still want to
        // print the high info, even if it is zero.
        if (show_high) {
            printf(
                "%-7s %10Lu %10Lu %10Lun", "Low:",
                S(kb_low_total),
                S(kb_low_total - kb_low_free),
                S(kb_low_free)
            );
            printf(
                "%-7s %10Lu %10Lu %10Lun", "High:",
                S(kb_high_total),
                S(kb_high_total - kb_high_free),
                S(kb_high_free)
            );
        }
        if(!old_fmt){
            unsigned KLONG buffers_plus_cached = kb_main_buffers + kb_main_cached;
            printf(
                "-/+ buffers/cache: %10Lu %10Lun",
                S(kb_main_used - buffers_plus_cached),
                S(kb_main_free + buffers_plus_cached)
            );
        }
        printf(
            "%-7s %10Lu %10Lu %10Lun", "Swap:",
            S(kb_swap_total),
            S(kb_swap_used),
            S(kb_swap_free)
        );
        if(show_total){
            printf(
                "%-7s %10Lu %10Lu %10Lun", "Total:",
                S(kb_main_total + kb_swap_total),
                S(kb_main_used  + kb_swap_used),
                S(kb_main_free  + kb_swap_free)
            );
        }
        if(pause_length){
        fputc('n', stdout);
        fflush(stdout);
        if (count != 1) usleep(pause_length);
    }
    } while(pause_length && --count);

    return 0;
}


Source Code Highlight

define S(X) ( ((unsigned long long)(X) << 10) >> shift)

it takes a number, X, casts it to a ‘long long’ (presumably the longest int type on your system ?) and then it left-shifts by 10 (meaning, the the positions of all bits are shifted 10 places to the left) only to shift it back right ‘shift’ number of positions.

source : nickname – psuedonymous. server – irc.freenode.net Featured Image FIXME

Related Knowledge

free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel. The shared memory column should be ignored; it is obsolete.

source : debian manual for free.

Nc - TCP/IP Swiss Army Knife

A UNIX Command

Window I Server

$nc -l -p  3333
hello
hello
how are you ?
fine

Window II client

$nc 127.0.0.1 3333
hello
hello
how are you ?
fine

Explanation

netcat is a simple unix utility which reads and writes data across network connections, using TCP or UDP protocol.

Related Source Code Exposition

doexec (fd)
  int fd;
{
  register char * p;

  dup2 (fd, 0);                         /* the precise order of fiddlage */
  close (fd);                           /* is apparently crucial; this is */
  dup2 (0, 1);                          /* swiped directly out of "inetd". */

  if (doexec_use_sh) {
Debug (("gonna exec "%s" using /bin/sh...", pr00gie))
    execl ("/bin/sh", "sh", "-c", pr00gie, NULL);
    bail ("exec %s failed", pr00gie);   /* this gets sent out.  Hmm... */
  }

  p = strrchr (pr00gie, '/');           /* shorter argv[0] */
  if (p)
    p++;
  else
    p = pr00gie;
Debug (("gonna exec %s as %s...", pr00gie, p))
  execl (pr00gie, p, NULL);
  bail ("exec %s failed", pr00gie);     /* this gets sent out.  Hmm... */
} /* doexec */

Source Code Highlight

fiddle all the file descriptors around, and hand off to another prog. Sort of like a one-off “poor man’s inetd”. This is the only section of code that would be security-critical, which is why it’s ifdefed out by default. Use at your own hairy risk; if you leave shells lying around behind open listening ports you deserve to lose!!

Featured Image FIXME

Related Knowledge

It has been suggested that the open() system call should get a flag which would cause it to select a non-sequential file descriptor from the outset, eliminating the need for a separate call to nonseqfd(). There are, however, a number of system calls which create file descriptors but which have no flags parameter and which, thus, will never be able to return non-sequential file descriptors; socket() is a classic example. So there will still be a need for a system call which can duplicate a file descriptor into the new space.

source : http://lwn.net/Articles/236843/

netcat examples

Good News

It is in living and acting that man establishes his relationship with being, with the truth and with the good. The artist has a special relationship to beauty. In a very true sense it can be said that beauty is the vocation bestowed on him by the Creator in the gift of artistic talent. And, certainly, this too is a talent which ought to be made to bear fruit, in keeping with the sense of the Gospel parable of the talents (cf. Mt 25:14-30).

Here we touch on an essential point. Those who perceive in themselves this kind of divine spark which is the artistic vocationas poet, writer, sculptor, architect, musician, actor and so onfeel at the same time the obligation not to waste this talent but to develop it, in order to put it at the service of their neighbour and of humanity as a whole.

John Paul II Letter to Artists, (April 4, 1999) The artistic vocation in the service of beauty

Setterm - Set Terminal Attributes

GNU Command
$setterm 
setterm: Argument error.

Usage:
 setterm [options]

Options:
 -term 
 -reset
 -initialize
 -cursor 
 -repeat 
 -appcursorkeys 
 -linewrap 
 -default
 -foreground 
 -background 
 -ulcolor 
 -ulcolor 
 -hbcolor 
 -hbcolor 
 -inversescreen 
 -bold 
 -half-bright 
 -blink 
 -reverse 
 -underline 
 -store >
 -clear 
 -tabs < tab1 tab2 tab3 ... >      (tabn = 1-160)
 -clrtabs < tab1 tab2 tab3 ... >   (tabn = 1-160)
 -regtabs <1-160>
 -blank <0-60|force|poke>
 -dump   <1-NR_CONSOLES>
 -append <1-NR_CONSOLES>
 -file dumpfilename
 -msg 
 -msglevel <0-8>
 -powersave 
 -powerdown <0-60>
 -blength <0-2000>
 -bfreq freqnumber
 -version
 -help

For more information see lsblk(1).
$





setterm sets terminal attributes.

Explanation

-cursor [on|off]
Turns the terminal's cursor on or off.

Related Source Code Exposition

        if (opt_cursor) {
                if (opt_cu_on)
                        putp(ti_entry("cnorm"));
                else
                        putp(ti_entry("civis"));
        }


Source Code Highlight
 -cursor [on|off].

Featured Image
FIXME

General Knowledge

A  terminal consists of  a screen  and keyboard  that one
uses  to  communicate   remotely  with  a  computer  (the
host). One uses it almost like it was a personal computer
but the terminal is remote from its host computer that it
communicates with (on the other  side of the room or even
on the other side of  the world). Programs execute on the
host  computer but  the results  display on  the terminal
screen.  Originally  terminals  were stand-alone  devices
with  no computational  ability and  thus they  were once
much cheaper in cost than computers. They had no pictures
or  audio, but  could  only display  text  and were  thus
called "text terminals". Today,  the cost of PC computers
is so low  that one may use a PC like  a text terminal by
running a software program to  make it behave like an old
text terminal. You formerly  found real text terminals at
libraries and schools.

Dig Domain Information Groper

GNU Command

$dig www.beautifulwork.org

; <<>> DiG 9.7.1-P2 <<>> www.beautifulwork.org
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21332
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.beautifulwork.org.     IN  A

;; ANSWER SECTION:
www.beautifulwork.org.  1554    IN  CNAME   beautifulwork.org.
beautifulwork.org.  1555    IN  A   66.232.98.219

;; Query time: 37 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Fri Feb 18 21:18:42 2011
;; MSG SIZE  rcvd: 69

$


$dig +nocomments +noanswer +noadditional +noquestion +nocmd www.beautifulwork.org
;; Query time: 36 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Fri Feb 18 21:21:56 2011
;; MSG SIZE  rcvd: 69

$


Explanation


dig (domain  information groper)  is a flexible  tool for
interrogating DNS  name servers. It  performs DNS lookups
and displays the answers  that are returned from the name
server(s) that were  queried. Most DNS administrators use
dig   to  troubleshoot  DNS   problems  because   of  its
flexibility, ease  of use  and clarity of  output.  Other
lookup tools tend to have less functionality than dig.


Related Source Code Exposition

#ifndef NOPOSIX

                INSIST(batchfp == NULL);
                homedir = getenv("HOME");
                if (homedir != NULL) {
                        unsigned int n;
                        n = snprintf(rcfile, sizeof(rcfile), "%s/.digrc",
                                     homedir);
                        if (n < sizeof(rcfile))
                                batchfp = fopen(rcfile, "r");
                }
                if (batchfp != NULL) {
                        while (fgets(batchline, sizeof(batchline),
                                     batchfp) != 0) {
                                debug("config line %s", batchline);
                                bargc = 1;
                                input = batchline;
                                bargv[bargc] = next_token(&input, " trn");
                                while ((bargv[bargc] != NULL) &&
                                       (bargc < 62)) {
                                        bargc++;
                                        bargv[bargc] =
                                                next_token(&input, " trn");
                                }

                                bargv[0] = argv[0];
                                argv0 = argv[0];

                                for(i = 0; i < bargc; i++)
                                        debug(".digrc argv %d: %s",
                                              i, bargv[i]);
                                parse_args(ISC_TRUE, ISC_TRUE, bargc,
                                           (char **)bargv);
                        }
                        fclose(batchfp);
                }
#endif


Source Code Highlight
Treat ${HOME}/.digrc as a special batchfile.


Featured Image

fixme 

True - Do Nothing, Successfully. False - Do Nothing, Unsuccessfully

GNU command

$true
$echo $?
0
$false
$echo $?
1
$
Explanation

true - do nothing, successfully
exit with a status code indicating success.
false - do nothing, unsuccessfully
exit with a status code indicating failure.
Related Source Code Exposition

int
main (int argc, char **argv)
{

  if (argc == 2)
    {
      initialize_main (&argc, &argv);
      set_program_name (argv[0]);
      setlocale (LC_ALL, "");
      bindtextdomain (PACKAGE, LOCALEDIR);
      textdomain (PACKAGE);

      atexit (close_stdout);

      if (STREQ (argv[1], "--help"))
        usage (EXIT_STATUS);

      if (STREQ (argv[1], "--version"))
        version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS,
                     (char *) NULL);
    }

  exit (EXIT_STATUS);
}

Source Code Highlight
Recognize --help or --version only if it's the only
command-line argument.
Featured Image
FIXME
Related Knowledge

`true' does  nothing except return  an exit status  of 0,
meaning "success".  It  can be used as a  place holder in
shell  scripts  where  a  successful command  is  needed,
although the  shell built-in  command `:' (colon)  may do
the same thing faster.   In most modern shells, `true' is
a built-in command,  so when you use `true'  in a script,
you're probably  using the built-in command,  not the one
documented here.

Note,  however, that it  is possible  to cause  `true' to
exit   with  nonzero   status:  with   the   `--help'  or
`--version'  option,  and  with standard  output  already
closed or redirected to a  file that evokes an I/O error.
For example, using a Bourne-compatible shell:

 $ ./true --version >&-
     ./true: write error: Bad file number
     $ ./true --version > /dev/full
     ./true: write error: No space left on device

This version of `true' is implemented as a C program, and
is  thus  more secure  and  faster  than  a shell  script
implementation, and  may safely be used as  a dummy shell
for the purpose of disabling accounts.
source : info coreutils 'true invocation'