Tuesday, December 21, 2010

C code: A small program to convert decimal number to binary digits.


Here its a small recursive function, which will convert a decimal value to binary digits.

#include <stdio.h>

void convert_binary(int a)
        return ;

int main()
    printf("Hello world!\n");
    convert_binary(130); // Here this recursive function will convert 130 to binary digits.
    return 0;

If you feel its good, give me a thanks !!!


C Threads : Two synchronized threads to print alternate numbers.

Here, i was trying to print alternate numbers starting from 0 to 11. I have two threads, one will always prints odd numbers and other will print only even number.

My intension is to print odd and even alternately. To ensure the synchronization, i am using MUTEXES.

Sample code :
pthread_mutex_lock (&mutexsum);
pthread_mutex_unlock (&mutexsum);

Full version of the code is as below. Here I use pthread libraries to create the threads.
My reference  : https://computing.llnl.gov/tutorials/pthreads/.

#include <iostream>
#include <pthread.h>
using namespace std;
pthread_mutex_t mutexsum;
int gCount=0;

void *odd(void* ptr)
   if(gCount%2==1) //If even
        pthread_mutex_lock (&mutexsum);
        pthread_mutex_unlock (&mutexsum);

void *even(void* ptr)
   if(gCount%2==0) //If even
        pthread_mutex_lock (&mutexsum);
        pthread_mutex_unlock (&mutexsum);

int main()

    pthread_t T_even, T_odd;
    int T_rt1,T_rt2;
    void *status;
    pthread_mutex_init(&mutexsum, NULL);
    std::cout << "Hello world!" << endl;
    int i=0; // this variable has no significance
    T_rt1= pthread_create(&T_odd,NULL,odd,&i); // here variable i has no significance. it can be null also. I am passing it as a trial


    return 0;

Send me your comments.

Tuesday, December 7, 2010

C Code: Functions to read a line from file, removing leading and trailing spaces from a string token and get token string.

* Function Name: read_line
* Description: get one line from /etc/passwd file. If there is a line contains
* more than LINE_MAX characters, it will ignore it and read the
* next line. It also handles continuation character '\'. It always
* leaves (or inserts) \n\0 at the end of the line.
* Parameters:
* FILE *f: file ptr points to /etc/passwd file
* char *buffer: char array
* size_t bufeln: length of buffer
* Return Value:
* int : It returns the length of the line read, excluding the \n\0.
static int read_line(
FILE *f,
char *buffer,
size_t buflen)
int linelen = 0;
char c;
int curlen = 0;
char *ret, *tempbuf;

tempbuf = buffer;
while (1) {
tempbuf += (unsigned)curlen;
/* buffer over flow, skip this long line */
if (tempbuf >= (buffer + buflen - 1))
do {
c = getc(f);
if (feof(f)) {
return (-1);
} while (c != '\n');
linelen = 0;
tempbuf = buffer;
curlen = 0;
ret = fgets(tempbuf, linelen == 0 ?
buflen : buflen - (unsigned)linelen, f);
curlen = strlen(ret);
linelen += curlen;
switch (ret == NULL ? EOF : ret[curlen - 1]) {
case EOF:
if (linelen == 0 ) {
/* The file was empty */
linelen = -1;
} else if (buffer[linelen] == '\\') {
/* We expected another line to append to previous
line as indicated by a trailing backslash, but the
file ended */
linelen = -1;
} else {
/* The file contained one line, and all is well */
buffer[linelen ] = '\n';
buffer[linelen + 1 ] = '\0';
return (linelen);
case '\n':
if (curlen > 1 &&
ret[curlen - 2] == '\\') {
curlen -= 2;
linelen -= 2;
} else {
ret[curlen - 1] = '\n';
ret[curlen ] = '\0';
return (linelen - 1);
} /* case */

* Function Name: gettok
* Description: parse one line read from /etc/passwd file, return pointer to the
* next passwd entry field
* Parameters:
* char **line_addr: address of the pointer that point to an array
* Return Value:
* char *p : pointer to an array
static char *gettok (char **line_addr)
char *q = *line_addr;
char *p = q;
while (*p && *p != ':' && *p != '\n')
if (*p == '\n')
*p = '\0';
else if (*p != '\0')
*p++ = '\0';
*line_addr = p;
return (q);

* Function Name: rm_leading_and_trailing_blank
* Description: Removes all the leading and trialing blanks in a string token.
* A string " This is a test " will be formatted to
* "This is a test"
* Cases like empty character string and character string with
* just a space or spaces are also covered. A string " "
* will be reduced to ""
* Parameters:
* target_string: string token.
* Return Value: None
static void rm_leading_and_trailing_blank(char *target_string)

char * mover = target_string;
char * current = target_string;

while (*mover != '\0' && (*mover == ' ' || *mover == '\t'))

*current = *mover;
current++, mover++;
*current = '\0';
while ( current >= target_string &&
(*current == ' ' || *current == '\t' || *current == '\n'))


Tuesday, October 12, 2010

HP-UX Directory Server components

Directory Server 8.1 is comprised of several components, which work in tandem:
• Directory Server
The Directory Server is the core LDAP server daemon. It is compliant with LDAP v3 standards. This component includes command-line server management and administration programs, and scripts for common operations like export and backing up databases.

• Directory Server Console
The Directory Server Console is the user interface that simplifies managing users, groups, and other LDAP data for your enterprise. The Console is used for all aspects of server management, including making backups; configuring security, replication, and databases; adding entries; and monitoring servers and viewing statistics.

• Administration Server
The Administration Server is the management agent that administers Directory Servers. It communicates with the Directory Server Console and performs operations on the Directory Server instances. It also provides a simple HTML interface and on-line help pages. There must be one Administration Server running on each machine that has a Directory Server
instance running on it.

• Port numbers
The Directory Server setup requires two TCP/IP port numbers: one for the Directory Server and one for the Administration Server. These port numbers must be unique. The Directory Server instance (LDAP) has a default port number of 389(non-secure, secure port is 636) . The Administration Server port number has a default number of 9830. Alternatively, you can assign any port number between 1025 and 65535 for the Directory Server and Administration Server ports; you are not required to use the defaults or the randomly-generated ports.

Thursday, September 16, 2010

Using C functions like malloc in C++.

#include iostream

using namespace std;
extern "C"
int puts(const char *); // Using C style functions in Cpp.
void * malloc(std::size_t);
int main()
puts("helo world ! ");
int *p;
p=(int *)malloc(sizeof(int));
return 0;

Wednesday, July 21, 2010

How google would generate new ideas

"An idea can change the world". But to have such an idea, you may need to pay your life. If you go with mathematical real analysis concept, the equation would transform to "one whole life would change the world".
So any inventor could have dream to get an idea, which could change the world. So, I could say, one idea is the most valuable stuff in the world. It may costs your life and will save lots of lives.
Google, the new generation platform for internet world. Google, started as a search engine and then become internet giant. We all will wonder when they come up with new products and idea. I always wonder, who pumps these much of ideas to them.

There might be lot many researches went on to trap the Google's idea treasure. Many assumptions or perceptions brought out by those researchers.

Today, I have started my day with a new idea. I discussed it with my friend. My friend asked me to search it on Google.
I compile the search string on Google, and before hitting the enter key I paused my self from doing so.

You know why ?

I got a spark, that why should I submit my new idea to Google corporation, though you are not intended to do so ?
Yes, if you are searching a new string, there can be mechanism to store it in Google servers to verify for a new idea to implement. I mean, if you search with new search string for finding similar items presented any where in the world. And when you found no similar idea available in internet, you got the trigger to start the research on the perception that, you are the only man knowing about it.
But is it really true ?
I believe there is another invisible, but more powerful man than you, seeing everything, obviously i didn't mean the God, behind the screen. Yes!!! Google eyes should closely watching it.

Their search engine could be the real treasure for their ideas, that change the world. Their algorithm might be like this.
1- Get the search string.
2- Check for unique or no search result.
3- Google will have a database for interested domain
4- Check for the string match with any of the data kept in Google interested domain.
5- If the new string matches with the Google's interest, take it to expert desk for further analysis.
6- Hence a new idea could be generated

The all above are my guess. I don't have any evidence for the above thoughts.

Wednesday, April 21, 2010

Memory leak management while using apache libraries

   I had faced a memory leak  issue when using apache APIs to create sockets. My application designs to monitor some set of ports continuously in a frequent time span. Application internally uses APIs from apache library to create memory pool, to create sockets, to shutdown socket etc..
First, it will create a pool of memory by using apr_pool_create function as below .
apr_pool_create(&newPool, NULL)

And then it makes a socket address with apr_sockaddr_info_get call as below.
//making socket address
apr_sockaddr_info_get(&remote_sa, dest, APR_UNSPEC,
(apr_uint16_t)portNum, 0, pool)

Then it creates a Socket as below.
apr_socket_create(&sock, remote_sa->family,
After creating socket, it tries binds to the port.
apr_bind(sock, remote_sa)
Then connect to the port and started listening for a connection request.
apr_connect(sock, remote_sa)

And then below functions are used for other usual socket activities.
apr_recv(sock, dataRecv, &length);

After the socket's tasks finished, we used to shutdown the socket and close for further actions.
apr_shutdown(sock, APR_SHUTDOWN_WRITE)

These all above code works in a while(1) loop. Creation of memory pool is a one time activity. Remaining tasks(from socket creation to socket closing) are continuously looped until application killed.
This application will be working as a process, which always present in active memory to listen the specified ports. I have received an issue from one of our customer saying that, he is observing a memory leak while running this process. I took this task and me too observed the same issue in my development server.
In general, reproducing a problem is the 60% of the solution. But, in memory leak problem, it will be only 40%. You may observe a leak, but you may not come to a conclusion that, this leak is happened by this reason.
I did a regular memory leak check up in the big code base. I searched from malloc, realloc, calloc etc. And I searched for any macros defined against malloc.

Nothing!!! No memory allocation calls used in the code. Then my spy glass went the the pool creation API (apr_pool_create). I observed that Memory pool is created but not freed any where. I have Apache API to delete the pool. But, if I delete the pool, application will be killed immediately. I wanted to retain my application in active memory unless, user forcefully killed him.

So I cant use apr_pool_destroy to release the memory pool. Then i visited Apache Portability Runtime library for the API reference . I found there is another call apr_pool_clear(pool) to clear the memory location. GOD GRACE. I did that !!!.
My issue is resolved. So whenever a new socket finished his tasks, he will clear the pool and return the handler to begin. And then new socket will allocate the memory from free pool. Hence no memory leak !!!

Tuesday, February 9, 2010

PHP Source code for comment box in unicode language(like malayalam, tamil and arabic)

        A comment box is a must have feature in many of the web based aplications. Users should able to save their comments on their own language. Many of the news papers are allowing their visitors to express their views about the articles/news published. Comment enabled web pages will increase user engagement, hence more income from advertisement venders can expect.
Making a comment box is nothing if you are using PHP and MySQL in most scenario.

1. Declare a Rich text box using HTML Tags.
2. On submit, collect the inserted values and save it to mySQL database, thats it.

Though, saving your text in mySQL database will be difficult if you are playing with Unicode charactors.  I know many of my friends are complaining about that. They were tried to save malayalam unicode characters and, while retrieving the saved text they got a bunch of question marks. 
They saved " ചേന്ദമംഗല്ലൂര്‍ നല്ലൊരു നാടാണല്ലൊ ... ഹി ഹി ഹി "
They recieved " ????????????????????????????  ??? "
Its because, unicode charaters are a unique special numercial codes for different languages. MySQL may not decode it to proper language representation unless you are explicity told to him. I have a solution for this problem.
1. Use SET NAMES 'utf8' before database transaction started.
2. Convert your table collation settings to  'utf8_general_ci'

visit my old post for more details about this .

Hope you understand the technique behind the unicode operations.  Now we can move into the coding part of the comment box. I have to PHP funcitons, which you can use for making a comment box in your web based aplication.

   1:  function commentbox($dcName,$docId,$act_page,$SecurePath="../../lib/",$security="secured")

   2:  {


   4:      echo("<form name='"."inputfrm"."' enctype='"."multipart/form-data"."' method='"."post"."' action='".$act_page."?mod=".$security. "' onSubmit='"."return ValidateForm()"."'>");

   5:      echo("<fieldset>");


   7:      echo("<textarea name='"."ta"."' rows='"."10"."' cols='"."50"."'></textarea>");

   8:      echo("<br>");

   9:      echo("Doc ID:"); 

  10:      echo("<input name='"."docId"."' type='"."text"."' value='".$docId."' size='"."5"."'  readonly='"."true"."'>");

  11:      echo("<br><br>");

  12:      echo("Name &nbsp;:"); 

  13:      echo("<input name='"."txtName"."' type='"."text"."' size='"."25"."'>");

  14:      echo("<font face='"."Verdana, Arial, Helvetica, sans-serif"."'>* (Mandatory)</font>");

  15:      echo("<br><br>");

  16:      echo("Email &nbsp;: ");

  17:      echo("<input name='"."txtEmail"."' type='"."text"."' size='"."50"."'>");


  19:      if($security=="secured")

  20:      {


  22:          echo("<table width='"."100%"."' border='"."0"."' cellspacing='"."0"."' cellpadding='"."0"."'><tr>");

  23:          echo("<td width='"."10%"."'>");

  24:          echo("<td width='"."80%"."'>");

  25:          //pass a session id to the query string of the script to prevent ie caching

  26:          echo("<br>");

  27:          echo("<img src='".$SecurePath."securimage_show.php?sid=".md5(uniqid(time()))."'><br/>");


  29:  //        echo("<img src='".$SecurePath."securimage_show.php><br />");

  30:          echo("<font color='"."#ff0000"."'>");

  31:          echo("Enter the string displayed above<br>");

  32:          echo("</font>");

  33:          echo("<input type='"."text"."' name='"."securityCode"."' /><br />");

  34:          echo("</td>");


  36:          echo("<td width='"."10%"."'>");

  37:          echo("</tr></table>");

  38:      }


  40:      echo("</p>");

  41:      echo("<p align='"."right"."'><input type='"."submit"."' value='"."Save Comment"."' /></p>");

  42:      echo("</fieldset>");

  43:      echo("</form>");

  44:  }

function insertComment($docName,$DocId,$uText,$Uname,$TxtEmail,$ipAdr=0)
include 'connect.php';
// echo($pageURL);
// $ipAdr ='';
$time = time(now);
$phptime=date('Y-m-d H:i:s', $time);
@mysql_query("SET NAMES 'utf8'",$id); /// Its very inportant to display or insert unicode characters in db
$unicodeText = preg_replace('#\r?\n#', '<br />', $uText);
$cQryPart="insert into document (docName, DocID, Comments, aproved, u_name, email,CDate,isSuspects,extra,extra2) values ";
$cQry=$cQryPart."('".$docName."',".$DocId.",'".$unicodeText."',".$aproved.",'".$Uname."','".$TxtEmail."','".$phptime."','".$isSuspects."','".$ipAdr."','".$pageURL."')" ;
// echo($cQry);
$cresult = @mysql_query($cQry,$id) or
die("Unable to Execute the query");