Search in shivacherukuri.tech@blogger.com

Thursday, March 18, 2010

Fw: how linux boots


How Linux boots

As it turns out, there isn't much to the boot process:

1. A boot loader finds the kernel image on the disk, loads it into memory, and starts it.
2. The kernel initializes the devices and its drivers.
3. The kernel mounts the root filesystem.
4. The kernel starts a program called init.
5. init sets the rest of the processes in motion.
6. The last processes that init starts as part of the boot sequence allow you to log in.

Identifying each stage of the boot process is invaluable in fixing boot problems and understanding the system as a whole. To start, zero in on the boot loader, which is the initial screen or prompt you get after the computer does its power-on self-test, asking which operating system to run. After you make a choice, the boot loader runs the Linux kernel, handing control of the system to the kernel.

There is a detailed discussion of the kernel elsewhere in this book from which this article is excerpted. This article covers the kernel initialization stage, the stage when the kernel prints a bunch of messages about the hardware present on the system. The kernel starts init just after it displays a message proclaiming that the kernel has mounted the root filesystem:

VFS: Mounted root (ext2 filesystem) readonly.

Soon after, you will see a message about init starting, followed by system service startup messages, and finally you get a login prompt of some sort.

NOTE On Red Hat Linux, the init note is especially obvious, because it "welcomes" you to "Red Hat Linux." All messages thereafter show success or failure in brackets at the right-hand side of the screen.

Most of this chapter deals with init, because it is the part of the boot sequence where you have the most control.
init

There is nothing special about init. It is a program just like any other on the Linux system, and you'll find it in /sbin along with other system binaries. The main purpose of init is to start and stop other programs in a particular sequence. All you have to know is how this sequence works.

There are a few different variations, but most Linux distributions use the System V style discussed here. Some distributions use a simpler version that resembles the BSD init, but you are unlikely to encounter this.

Runlevels

At any given time on a Linux system, a certain base set of processes is running. This state of the machine is called its runlevel, and it is denoted with a number from 0 through 6. The system spends most of its time in a single runlevel. However, when you shut the machine down, init switches to a different runlevel in order to terminate the system services in an orderly fashion and to tell the kernel to stop. Yet another runlevel is for single-user mode, discussed later.

The easiest way to get a handle on runlevels is to examine the init configuration file, /etc/inittab. Look for a line like the following:

id:5:initdefault:

This line means that the default runlevel on the system is 5. All lines in the inittab file take this form, with four fields separated by colons occurring in the following order:
# A unique identifier (a short string, such as id in the preceding example)
# The applicable runlevel number(s)
# The action that init should take (in the preceding example, the action is to set the default runlevel to 5)
# A command to execute (optional)

There is no command to execute in the preceding initdefault example because a command doesn't make sense in the context of setting the default runlevel. Look a little further down in inittab, until you see a line like this:

l5:5:wait:/etc/rc.d/rc 5

This line triggers most of the system configuration and services through the rc*.d and init.d directories. You can see that init is set to execute a command called /etc/rc.d/rc 5 when in runlevel 5. The wait action tells when and how init runs the command: run rc 5 once when entering runlevel 5, and then wait for this command to finish before doing anything else.

There are several different actions in addition to initdefault and wait, especially pertaining to power management, and the inittab(5) manual page tells you all about them. The ones that you're most likely to encounter are explained in the following sections.

respawn

The respawn action causes init to run the command that follows, and if the command finishes executing, to run it again. You're likely to see something similar to this line in your inittab file:

1:2345:respawn:/sbin/mingetty tty1

The getty programs provide login prompts. The preceding line is for the first virtual console (/dev/tty1), the one you see when you press ALT-F1 or CONTROL-ALT-F1. The respawn action brings the login prompt back after you log out.

ctrlaltdel

The ctrlaltdel action controls what the system does when you press CONTROL-ALT-DELETE on a virtual console. On most systems, this is some sort of reboot command using the shutdown command.

sysinit

The sysinit action is the very first thing that init should run when it starts up, before entering any runlevels.

How processes in runlevels start

You are now ready to learn how init starts the system services, just before it lets you log in. Recall this inittab line from earlier:

l5:5:wait:/etc/rc.d/rc 5

This small line triggers many other programs. rc stands for run commands, and you will hear people refer to the commands as scripts, programs, or services. So, where are these commands, anyway?

For runlevel 5, in this example, the commands are probably either in /etc/rc.d/rc5.d or /etc/rc5.d. Runlevel 1 uses rc1.d, runlevel 2 uses rc2.d, and so on. You might find the following items in the rc5.d directory:

S10sysklogd S20ppp S99gpm
S12kerneld S25netstd_nfs S99httpd
S15netstd_init S30netstd_misc S99rmnologin
S18netbase S45pcmcia S99sshd
S20acct S89atd
S20logoutd S89cron

The rc 5 command starts programs in this runlevel directory by running the following commands:

S10sysklogd start
S12kerneld start
S15netstd_init start
S18netbase start
...
S99sshd start

Notice the start argument in each command. The S in a command name means that the command should run in start mode, and the number (00 through 99) determines where in the sequence rc starts the command.

The rc*.d commands are usually shell scripts that start programs in /sbin or /usr/sbin. Normally, you can figure out what one of the commands actually does by looking at the script with less or another pager program.

You can start one of these services by hand. For example, if you want to start the httpd Web server program manually, run S99httpd start. Similarly, if you ever need to kill one of the services when the machine is on, you can run the command in the rc*.d directory with the stop argument (S99httpd stop, for instance).

Some rc*.d directories contain commands that start with K (for "kill," or stop mode). In this case, rc runs the command with the stop argument instead of start. You are most likely to encounter K commands in runlevels that shut the system down.

Adding and removing services

If you want to add, delete, or modify services in the rc*.d directories, you need to take a closer look at the files inside. A long listing reveals a structure like this:

lrwxrwxrwx . . . S10sysklogd -> ../init.d/sysklogd
lrwxrwxrwx . . . S12kerneld -> ../init.d/kerneld
lrwxrwxrwx . . . S15netstd_init -> ../init.d/netstd_init
lrwxrwxrwx . . . S18netbase -> ../init.d/netbase
...

The commands in an rc*.d directory are actually symbolic links to files in an init.d directory, usually in /etc or /etc/rc.d. Linux distributions contain these links so that they can use the same startup scripts for all runlevels. This convention is by no means a requirement, but it often makes organization a little easier.

To prevent one of the commands in the init.d directory from running in a particular runlevel, you might think of removing the symbolic link in the appropriate rc*.d directory. This does work, but if you make a mistake and ever need to put the link back in place, you might have trouble remembering the exact name of the link. Therefore, you shouldn't remove links in the rc*.d directories, but rather, add an underscore (_) to the beginning of the link name like this:

mv S99httpd _S99httpd

At boot time, rc ignores _S99httpd because it doesn't start with S or K. Furthermore, the original name is still obvious, and you have quick access to the command if you're in a pinch and need to start it by hand.

To add a service, you must create a script like the others in the init.d directory and then make a symbolic link in the correct rc*.d directory. The easiest way to write a script is to examine the scripts already in init.d, make a copy of one that you understand, and modify the copy.

When adding a service, make sure that you choose an appropriate place in the boot sequence to start the service. If the service starts too soon, it may not work, due to a dependency on some other service. For non-essential services, most systems administrators prefer numbers in the 90s, after most of the services that came with the system.

Linux distributions usually come with a command to enable and disable services in the rc*.d directories. For example, in Debian, the command is update-rc.d, and in Red Hat Linux, the command is chkconfig. Graphical user interfaces are also available. Using these programs helps keep the startup directories consistent and helps with upgrades.

HINT: One of the most common Linux installation problems is an improperly configured XFree86 server that flicks on and off, making the system unusable on console. To stop this behavior, boot into single-user mode and alter your runlevel or runlevel services. Look for something containing xdm, gdm, or kdm in your rc*.d directories, or your /etc/inittab.

Controlling init

Occasionally, you need to give init a little kick to tell it to switch runlevels, to re-read the inittab file, or just to shut down the system. Because init is always the first process on a system, its process ID is always 1.

You can control init with telinit. For example, if you want to switch to runlevel 3, use this command:

telinit 3

When switching runlevels, init tries to kill off any processes that aren't in the inittab file for the new runlevel. Therefore, you should be careful about changing runlevels.

When you need to add or remove respawning jobs or make any other change to the inittab file, you must tell init about the change and cause it to re-read the file. Some people use kill -HUP 1 to tell init to do this. This traditional method works on most versions of Unix, as long as you type it correctly. However, you can also run this telinit command:

telinit q

You can also use telinit s to switch to single-user mode.

Shutting down

init also controls how the system shuts down and reboots. The proper way to shut down a Linux machine is to use the shutdown command.

There are two basic ways to use shutdown. If you halt the system, it shuts the machine down and keeps it down. To make the machine halt immediately, use this command:

shutdown -h now

On most modern machines with reasonably recent versions of Linux, a halt cuts the power to the machine. You can also reboot the machine. For a reboot, use -r instead of -h.

The shutdown process takes several seconds. You should never reset or power off a machine during this stage.

In the preceding example, now is the time to shut down. This argument is mandatory, but there are many ways of specifying it. If you want the machine to go down sometime in the future, one way is to use +n, where n is the number of minutes shutdown should wait before doing its work. For other options, look at the shutdown(8) manual page.

To make the system reboot in 10 minutes, run this command:

shutdown -r +10

On Linux, shutdown notifies anyone logged on that the machine is going down, but it does little real work. If you specify a time other than now, shutdown creates a file called /etc/nologin. When this file is present, the system prohibits logins by anyone except the superuser.

When system shutdown time finally arrives, shutdown tells init to switch to runlevel 0 for a halt and runlevel 6 for a reboot. When init enters runlevel 0 or 6, all of the following takes place, which you can verify by looking at the scripts inside rc0.d and rc6.d:

1. init kills every process that it can (as it would when switching to any other runlevel).

# The initial rc0.d/rc6.d commands run, locking system files into place and making other preparations for shutdown.
# The next rc0.d/rc6.d commands unmount all filesystems other than the root.
# Further rc0.d/rc6.d commands remount the root filesystem read-only.
# Still more rc0.d/rc6.d commands write all buffered data out to the filesystem with the sync program.
# The final rc0.d/rc6.d commands tell the kernel to reboot or stop with the reboot, halt, or poweroff program.

The reboot and halt programs behave differently for each runlevel, potentially causing confusion. By default, these programs call shutdown with the -r or -h options, but if the system is already at the halt or reboot runlevel, the programs tell the kernel to shut itself off immediately. If you really want to shut your machine down in a hurry (disregarding any possible damage from a disorderly shutdown), use the -f option.


--
siva
09886179349

Rreverse of string without using extra memory or swaping



/* Following code does as intended */
#include <stdio.h>
 
#define REVERSE_STRING(X) Rstring(X, *(X), strlen(X)-1)
 
void Rstring( char *str, char c, int index )
{
        if( index != 0 )
               Rstring( str, *(str+(strlen(str))-index),
index-1);     
        *(str+index) = c;             
}
 
int main( void )
{
        char str[] = "Dharmendra Patel";
        printf("Actual string is [%s]\n", str);
        REVERSE_STRING(str);
        printf("Reversed string is [%s]\n", str);
        return 0;
}


[tech] xor list


XOR list example

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct xnode {
 int data;
 unsigned long direction;
};

struct xnode *add_data(int data, struct xnode* list);
void walk_list(struct xnode *list);
int main(void) {

 struct xnode *l2 = add_data(2, NULL);
 struct xnode *l1 = add_data(1, l2);
 struct xnode *l3 = add_data(3, l2);
 struct xnode *l4 = add_data(4, l3);

 printf("front -> back....\n");
 walk_list(l1);
 printf("back -> front....\n");
 walk_list(l4);

 return 0;
}

struct xnode *add_data(int data, struct xnode *list) {
 struct xnode *newxnode = malloc(sizeof(struct xnode));

 assert(newxnode);
 newxnode->direction = (unsigned long)list;
 newxnode->data = data;

 if(list != NULL)
  list->direction ^= (unsigned long)newxnode;

 return newxnode;
}

void walk_list(struct xnode *list) {
 unsigned long prev = 0;

 while(list != NULL) {
  unsigned long next = prev ^ list->direction;
  printf("%d ", list->data);
  prev = (unsigned long)list;
  list = (struct xnode *)next;
 }

 printf("\n");
}

Fw: [tech] spanning tree protocol




Fw: [tech] Hash example in C



Hash example

Basic hash example

#include <stdio.h>
#include <stdlib.h>

#define HASHSIZE    1000
#define MAXLINE     1024

typedef struct tnode {
 char *data;
 struct tnode *next;
} node;

void htable_init(node *hashtable);                        // fire up hashtable
void htable_insert(node *hashtable, char *str);           // insert data into hashtable
void htable_resolve(node *hashtable, int loc, char *str); // resolve collisions in hashtable
void htable_display(node *hashtable);                     // display hashtable
int  htable_delete(node *hashtable, char *str);           // delete an entry from hashtable
int  htable_hash(char *str);                              // hash data for hashtable

int main(void) {
 char line[MAXLINE];
 node *hashtable;

 hashtable = (node *)malloc(HASHSIZE * sizeof(node));

 htable_init(hashtable);

 while((fgets(line, MAXLINE, stdin)) != NULL)
  htable_insert(hashtable, line);

 htable_display(hashtable);

 return 0;
}

/* fire up hashtable */
void htable_init(node *hashtable) {
 int i = 0;

 for(i = 0; i < HASHSIZE; i++)
  hashtable[i].data = NULL, hashtable[i].next = NULL;
}

/* insert data into hashtable */
void htable_insert(node *hashtable, char *str) {
 int index = 0;
 
 /*
 // determine hash function
 */
 index = htable_hash(str);
 if(hashtable[index].data != NULL) {
  /*
  // collision occurs - resolve by chaining
  */
  htable_resolve(hashtable, index, str);
 } else {
  hashtable[index].data = calloc(strlen(str) + 1, sizeof(char));
  strcpy(hashtable[index].data, str);
 }
}

/* hash data for hashtable */
int htable_hash(char *str) {
 int index = 0;
 char *tmp = NULL;

 tmp = calloc(strlen(str) + 1, sizeof(char));
 strcpy(tmp, str);

 while(*tmp) {
  index += *tmp;
  tmp++;
 }

 index = index % HASHSIZE;
 return index;
}

/* resolve collisions in hashtable */
void htable_resolve(node *hashtable, int loc, char *str) {
 node *tmp;
 tmp = hashtable + loc;

 while(tmp->next != NULL)
  tmp = tmp->next;
  tmp->next = (node *)malloc(sizeof(node));
  tmp->next->data = calloc(strlen(str) + 1, sizeof(char));
  strcpy(tmp->next->data, str);
  tmp->next->next = NULL;
}

/* display hashtable */
void htable_display(node *hashtable) {
 int i = 0;
 node *target;

 for(i = 0; i < HASHSIZE; i++) {
  if(hashtable[i].data != NULL) {
   target = hashtable + i;
   while(target)
    /* printf("location: %d, data: %s", i, target->data), target = target->next; */
    printf("%s", target->data), target = target->next;
  } /* if */
 } /* for */
}

/* delete an entry from hashtable */
int htable_delete(node *hashtable, char *str) {
 node *bla;
 node *blb;
 char *tmp = NULL;
 int index = 0;

 index = htable_hash(str);

 /* no item at this location */
 if(hashtable[index].data == NULL)
  return 1;

 /* only one item at this location */
 if(hashtable[index].next == NULL) {
  if(strcmp(hashtable[index].data, str) == 0) {
   /* item found */
   tmp = hashtable[index].data;
   hashtable[index].data = NULL;
   free(tmp);
  }
 } else {
  /* there is a chaining case */
  bla = hashtable + index;
  /* linked list similar */
  while(bla->next != NULL) {
   if(strcmp(bla->next->data, str) == 0) {
    blb = bla->next;
    if(bla->next->next)
     bla->next = bla->next->next;
    else
     bla->next = NULL;

    free(blb);
   } /* if */
  } /* while */
 } /* else */

 return 0;
}

Using setsockopt


#//using setsockopt

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

void
usage()
{
    printf("usage: setsock [-s <size>]\n");
    exit(1);
}

main(argc,argv)
int argc;
char **argv;
{
    char           c;
    unsigned int   ksize;
    int            fd;
    int            ret;
    unsigned long  size;
    socklen_t      len;

    while (( c = getopt (argc, argv, "s:")) != EOF) {
        switch (c) {
           case 's':
               ksize = atoi(optarg);
               break;
           default:
               usage();
        }
    }

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd) {
        printf("socket call failed.\n");
        exit(1);
    }

    size = ksize * 1024;

    ret = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(size));
    if (0 == ret) {
        printf("Successfully set the socket send buf size to %lu\n", size);
        len = sizeof(size);
        ret = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size,
                         (int *)&len);
        printf("getsockopt ret is %d. errno is %d. len is %d, "
               "size is %lu\n", ret,
               errno, len, size);
        exit(0);
    }

    printf("Failed to set the socket send buf size to %lu.  "
           "ret = %d, errno = %d.\n",
           ret, size, errno);
        ret = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size,
                         (int *)&len);
        printf("getsockopt ret is %d. errno is %d. len is %d, "
               "size is %lu\n", ret,
               errno, len, size);
    exit(1);
}

Fw: pmem.c


-->
#// p mem.c

#include <stdio.h>
#include <errno.h>
#include <sys/pstat.h>

main(argc, argv)
int argc;
char **argv;
{
  struct pst_status pst;
  unsigned int pid;
  unsigned int pages;
  int ret;
  int i;
  for (i=1; i<argc; i++) {
    pid = atoi(argv[i]);
    ret = pstat_getproc(&pst, sizeof(pst), 0, pid);
    if (ret == 1) {
      pages = 0
        + pst.pst_vtsize
        + pst.pst_vdsize
        + pst.pst_vssize
        + pst.pst_vshmsize
        + pst.pst_vmmsize
        + pst.pst_vusize
        + pst.pst_iosize
        ;
      printf("%d: vtsize=%dK\n", pid, 4 * pst.pst_vtsize);
      printf("%d: vdsize=%dK\n", pid, 4 * pst.pst_vdsize);
      printf("%d: vssize=%dK\n", pid, 4 * pst.pst_vssize);
      printf("%d: vshmsize=%dK\n", pid, 4 * pst.pst_vshmsize);
      printf("%d: vmmsize=%dK\n", pid, 4 * pst.pst_vmmsize);
      printf("%d: vusize=%dK\n", pid, 4 * pst.pst_vusize);
      printf("%d: iosize=%dK\n", pid, 4 * pst.pst_iosize);
      printf("%d: %dK\n", pid, 4 * pages);
    }
  }
}

Wednesday, March 10, 2010

Diff between variable and referrence


I know references are syntactic sugar, so easier code to read and write :)
But what are the differences?
Summary from answers and links below:
<![if !supportLists]>1.    <![endif]>A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
<![if !supportLists]>2.    <![endif]>A pointer can point to NULL while reference can never point to NULL
<![if !supportLists]>3.    <![endif]>You can't take the address of a reference like you can with pointers
<![if !supportLists]>4.    <![endif]>There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).
To clarify a misconception:
The C++ standard is very careful to avoid dictating how a compiler must implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:
int &ri = i;

allocates the same amount of storage as a pointer, and places the address of i into that storage.
So pointer and reference occupies same amount of memory
As a general rule,
<![if !supportLists]>·         <![endif]>Use references in function parameters and return types to define attractive interfaces.
<![if !supportLists]>·         <![endif]>Use pointers to implement algorithms and data structures.

1) A pointer can be re-assigned:
int x = 5;
 int y = 6;
 int *p;
 p =  &x;
 p = &y;
 *p = 10;
 assert(x == 5);
 assert(y == 10);
 
 
A reference cannot, and must be assigned at initialization:
int x = 5;
 int y = 6;
 int &r = x;
 
 
2) A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack vs heap. This implies that there is real a address of a reference that the compiler will not tell you.
int x = 0;
 int &r = x;
 int *p = &x;
 int *p2 = &r;
 assert(p == p2);
 
 
3) you can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer 1 level of indirection.
int x = 0;
 int y = 0;
 int *p = &x;
 int *q = &y;
 int **pp = &p;
 pp = &q;//*pp = q
 **pp = 4;
 assert(y == 4);
 assert(x == 0);
 
 
4) Pointer can be assigned NULL directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference NULL. Likewise, if you try hard enough you can have a reference to a pointer, and then that reference can contain NULL.
int *p = NULL;
 int &r = NULL; <--- compiling error
 
 
5) Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.
6) A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a .
7) A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address the item it references.
8) References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb

Monday, March 1, 2010

how to find bigendianness

FYI,

int am_big_endian() {

 

 long one = 1;

 printf(" &one :%p \n, (char *)(&one) :%p \n *((char *)(&one)): %c\n", \

          &one, (char *)(&one), (*((char *)(&one))) );

 

 return !(*((char *)(&one)));

}

 

  int am_big_endian2()

  {

      union { long l; char c[sizeof (long)]; } u;

      u.l = 1;

      return (u.c[sizeof (long) - 1] == 1);

  }

 

int main(void) {

 

  printf("Hi..my endianness is\n");

  printf("Big endian = %d \n",am_big_endian2());

  return 0;

}