Showing posts with label LINUX. Show all posts
Showing posts with label LINUX. Show all posts

Sunday, December 31, 2017

multi threaded quick sort using pthreads in C/C++

multi threaded quick sort using pthreads in C/C++

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

using namespace std;

int i=0;
pthread_t threads[5];


int x[20];

struct thread_data{
    int  upper_bound;
    int lower_bound;
    int *arr;
};
int semid;



void set_sem()
{
    semid=semget(12345,1,IPC_CREAT|0666);
    perror("semget");
    semctl(semid,0,SETVAL,5);
}
int get_sem()
{
    return semctl(semid,0,GETVAL,0);
}

void create_thread(int x[20], int first, int last);


sembuf psembuf={0,-1,SEM_UNDO};
sembuf vsembuf={0,1,SEM_UNDO};


void *quicksort(void *threadarg)
{

    int getv;
    semop(semid,&psembuf,1);
    getv=get_sem();
    cout<<"semaphore value  decrease to  "<<getv;
    struct thread_data *my_data;
    my_data = (struct thread_data *) threadarg;
    int first,last;
    first=my_data->upper_bound;
    last=my_data->lower_bound;
     int pivot,j,temp,i;
    if(first<last){
        pivot=first;
        i=first;
        j=last;
        cout<<"\nbefore done firts loop i = "<<i<<"j="<<j<<endl;
        for(int w=first;w<=last;w++) {
         
            cout<<endl<<"x["<<w<<"] ="<< *((my_data->arr) +w)<<endl;
        }
        while(i<j){
            while(*((my_data->arr)+i) <= *((my_data->arr)+pivot) && i<last)
                i++;
            while(*((my_data->arr)+j) > *((my_data->arr)+pivot) && j>first)
                j--;
            if(i<j){
                temp=*((my_data->arr)+i);
                *((my_data->arr)+i)=*((my_data->arr)+j);
                *((my_data->arr)+j)=temp;
            }
         
        }
        cout<<"\ndone firts loop\n"<<endl<<first<<endl<<last<<endl;

        temp=*((my_data->arr)+pivot);
        *((my_data->arr)+pivot)=*((my_data->arr)+j);
        *((my_data->arr)+j)=temp;
        for(int t = first;t<=last;t++)
            cout<<*((my_data->arr)+t)<<endl;
        for(int w=first;w<=last;w++) {
         
            cout<<endl<<"x["<<w<<"] ="<< my_data->arr[w]<<endl;
        }
        if (first < j-1) {
            cout<<"create thread first = "<<first<<"last = "<<j-1<<endl;
            create_thread(x,first,j-1);
        }
        else if (first == j-1 && my_data->arr[first]>my_data->arr[j]) {
            temp = my_data->arr[first];
            my_data->arr[first] = my_data->arr[j];
            my_data->arr[j] = temp;
        }

        if (j+1<last)
        {
            cout<<"create thread first = "<<j+1<<"last = "<<last<<endl;
            create_thread(x,j+1,last);
        }
        else if (j+1 == last && my_data->arr[last]< my_data->arr[j])
        {
            temp = my_data->arr[last];
            my_data->arr[last] = my_data->arr[j];
            my_data->arr[j] = temp;
        }
     
    }

 
 
 
    semop(semid,&vsembuf,1);

    // pthread_exit(NULL);
}


void create_thread(int x[20],int first, int last)
{
    int rc=0;
    i++;

    pthread_attr_t attr;
    void *status;
    int  getv;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    cout<<" entered create thread" << i <<endl<<"first"<<first<<"last"<<last;
    struct thread_data td;
    td.upper_bound=first;
    td.lower_bound=last;
    td.arr=x;
    getv=get_sem();
    cout<<"semaphore value is  "<<getv<<endl;
    if(getv <  1 )
    {
        sleep(5);
    } 
    rc = pthread_create(&threads[i], NULL,
            quicksort, (void *)&td);
    if (rc){
        cout << "Error:unable to create thread," << rc << endl;
        exit(-1);
    }


    pthread_attr_destroy(&attr);
    rc = pthread_join(threads[i], &status);
    if (rc){
        cout << "Error:unable to join," << rc << endl;
        exit(-1);
    }

    cout<<"existing";

 
}


int main()
{

    int size,i;

    cout<<"Enter size of the array: ";
    cin>>size;

    cout<<"Enter  elements: ";
    for(i=0;i<size;i++)
        cin>>x[i];
    cout<<" hello "<<endl;


    set_sem();

    cout<<"semaphore set to "<<get_sem();
    create_thread(x,0,size-1);

    cout<<"Sorted elements: "<<endl;
    for(i=0;i<size;i++)
        cout<<x[i]<<" "<<endl;

    return 0;
}

Wednesday, June 7, 2017

Wordament Boggle solver

Here is the code which will work on all unix systems and give all the words that can be formed in wordament game.

Few highlights for the code :

1) Code can be easily modified to give only big words for more points.
2) Also longer words are printed first. This feature can also be easily changed.
3) To compile the code just use g++ compiler. (g++ test.cpp).
4) and run it using ./a.out
5) input the wordament game in row first format.
6) This code was written using code from g4g site.
7) I combined the code given in "g4g boggle solver" and "g4g tries" and combined them to solve wordament.

Code :
 
#include<iostream>
#include<cstring>
#include <vector>
#include <fstream>
#include <algorithm>
#include <pthread.h>
using namespace std;

#define M 4
#define N 4
#define MAX 15
#define MIN 7

struct TrieNode *dictionary;//  = getNode();

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)

// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

string boggle[M][N];// = {{'G','I','Z'},
// trie node
vector<string> ans;

struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];

// isLeaf is true if the node represents
// end of a word
bool isLeaf;
};

// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
struct TrieNode *pNode = NULL;

pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

if (pNode)
{
int i;

pNode->isLeaf = false;

for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}

return pNode;
}

// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;

struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();

pCrawl = pCrawl->children[index];
}

// mark last node as leaf
pCrawl->isLeaf = true;
}

// Returns true if key presents in trie, else false
bool search(struct TrieNode *root, string key)
{
int level;
int length = key.size();
int index;
struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);

if (!pCrawl->children[index])
return false;

pCrawl = pCrawl->children[index];
}

return (pCrawl != NULL && pCrawl->isLeaf);
}




// A given function to check if a given string is present in
// dictionary. The implementation is naive for simplicity. As
// per the question dictionary is givem to us.
bool isWord(string &str)
{
if (search(dictionary, str) != 0)
return true;
return false;
}

// A recursive function to print all words present on boggle
void findWordsUtil(bool visited[M][N], int i,
int j, string &str, int size)
{
// Mark current cell as visited and append current character
// to str
//int size;
visited[i][j] = true;
str = str + boggle[i][j];
size = size+boggle[i][j].size();

// If str is present in dictionary, then print it
if (size<= MAX  && size>=MIN && isWord(str))
ans.push_back(str);//cout << str << endl;

// Traverse 8 adjacent cells of boggle[i][j]
for (int row=i-1; row<=i+1 && row<M; row++)
for (int col=j-1; col<=j+1 && col<N; col++)
if (row>=0 && col>=0 && !visited[row][col])
findWordsUtil(visited, row, col, str, size);

// Erase current character from string and mark visited
// of current cell as false
str.erase(str.length()-boggle[i][j].size());
size = size - boggle[i][j].size();
visited[i][j] = false;
}

// Prints all words present in dictionary.
void findWords() {
bool visited[M][N] = {{false}};
string str = "";
for (int i=0; i<M; i++)
      for (int j=0; j<N; j++)
findWordsUtil(visited, i, j, str, 0);

}

int all_chars(string s) {
int t = s.size();
for (int i  = 0; i<t; i++) {
if (!(s[i] >= 'a' && s[i] <= 'z'))
return 0;
}
return 1;
}

void load_dictionary() {
string line;
int n = 0;
ifstream myfile("/usr/share/dict/words");
dictionary = getNode();
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//std::transform(line.begin(), line.end(), line.begin(), ::tolower);
//dictionary.push_back(line);
if (all_chars(line) && line.size()<=MAX && line.size()>=MIN) {
insert(dictionary, line);
n++;
}
}
myfile.close();
}
cout <<"words added = "<<n<<endl;
}


void enter_boog(string boggle[M][N]) {
int i,j;
for (i= 0; i<M; i++) {
for (j = 0; j<N; j++) {
cin>>boggle[i][j];
}
}
}

bool compare(string s1, string s2) {
int i = s1.size();
int j = s2.size();
if ( i != j)
return i > j;
else
return (s1[0] - s2[0] > 0);
}
void display_words() {
sort(ans.begin(), ans.end(), compare);
for (int i=0; i<ans.size(); i++) {
cout<<ans[i]<<endl;
}
}
// Driver program to test above function
int main()
{
load_dictionary();
while (1) {
cout<<"enter boggle matrix";
enter_boog(boggle);
for (int i= 0; i<M; i++) {
for (int j = 0; j<N; j++) {
cout<<boggle[i][j]<<" ";
}
cout<<endl;
}

cout << "Following words of dictionary are present\n";

findWords();
display_words();
ans.resize(0);
}
return 0;
}


Tuesday, January 31, 2017

Important interview questions on OS (Operating Systems)

OS Concepts
o What do the system calls fork(), vfork(), exec(), wait(), waitpid() do?
Whats a Zombie process? Whats the difference between fork() and
vfork()?
o How does freopen() work? *
o What are threads? What is a lightweight process? What is a heavyweight
process? How different is a thread from a process? *
o How are signals handled? *
o What is a deadlock? *
o What are semaphores? *
o What is meant by context switching in an OS?*
o What is Belady's anomaly?
o What is thrashing?*
o What are short-, long- and medium-term scheduling?
o What are turnaround time and response time?
o What is the Translation Lookaside Buffer (TLB)?
o What is cycle stealing?
o What is a reentrant program?
o When is a system in safe state?
o What is busy waiting?
o What is pages replacement? What are local and global page
replacements?*
o What is meant by latency, transfer and seek time with respect to disk I/O?
o What are monitors? How are they different from semaphores?*
o In the context of memory management, what are placement and
replacement algorithms?
o What is paging? What are demand- and pre-paging?*
o What is mounting?
o What do you mean by dispatch latency?
o What is multi-processing? What is multi-tasking? What is multithreading?
What is multi-programming?*
o What is compaction?
o What is memory-mapped I/O? How is it different frim I/O mapped I/O?
o List out some reasons for process termination.

Saturday, April 13, 2013

Best way to do calculations on linux console

I always used shell to do all calculation stuff but using it can be sometimes can be a little tricky.

Then I came across python doing calculations on python is very very simple.

Example : 

console[1] python
Python 2.4.3 (#1, Dec 22 2011, 12:12:01)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t1 = 32*60 +8.1
>>> t2 = 33 *60 +35.1
>>> (t2-t1)/t2
0.043174036027988687
>>>



So you just have to type python and start doing calculations.

Friday, April 12, 2013

command to view memory and processor details in linux

To view cpu info and memory info in linux you can simply cat the related proc files.

cat /proc/cpuinfo -- for cpuinfo

cat /proc/meminfo -- for memory info
For example :

the command :
cat /proc/cpuinfo

will give output :

 cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 0
siblings        : 4
core id         : 0
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6004.26
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 1
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 1
siblings        : 4
core id         : 4
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.25
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 2
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 0
siblings        : 4
core id         : 2
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6043.37
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 3
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 1
siblings        : 4
core id         : 6
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.28
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 4
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 0
siblings        : 4
core id         : 1
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.17
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 5
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 1
siblings        : 4
core id         : 5
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.25
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 6
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 0
siblings        : 4
core id         : 3
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.20
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
processor       : 7
vendor_id       : GenuineIntel
cpu family      : 6
model           : 7
model name      : Intel(R) Xeon(R) CPU           E5450  @ 3.00GHz
stepping        : 10
cpu MHz         : 3000.114
cache size      : 6144 KB
physical id     : 1
siblings        : 4
core id         : 7
cpu cores       : 4
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall lm pni monitor ds_cpl est tm2 cx16 xtpr lahf_lm
bogomips        : 6000.24
clflush size    : 64
cache_alignment : 64
address sizes   : 38 bits physical, 48 bits virtual
power management:
 


Hard Disk Drive (HDD) not working on windows 7 after formatting it on Ubuntu ?


I formatted my Western Digital 500 Gb hard disk on Ubuntu 10.4 and now I want to use it on Windows 7 but it cannot detect it.
I formatted it with FAT(applicable to all) option.
I tried to Google this problem a bit and as suggested by one of the site i tried to format this drive with NTFS. Still windows cannot detect it.
Drives in windows 7 is not a problem because I tried a different usb drive on it and it works.
I can see the led of the drive glow when I connect it and I can also see remove drive safely option in lower right corner, but i cannot see any option in "my computer" to access the hard disk.


Solution:


I tried to format my HDD using "diskpart" utility available on widows7. It is working now.
Just run "diskpart" on command-promt on diskpart select your HDD and run following commands:
CLEAN
CREATE PARTITION PRIMARY 
SELECT PARTITION 1
ACTIVE
FORMAT FS=FAT32 QUICK
ASSIGN
EXIT
 

Saturday, April 6, 2013

Linux interview Questions --- Question 1

Difference between '>' and '|' in linux ?

'>'(redirection) will redirect the output of any command to any file.

eg.

ls -al > list.txt


copies the output of "ls -al" to "list.txt".
Now

'|' (pipe) is used when we want to use output of one command as input to another command.

eg.
ls -al | grep myfile


search my file in the list of files in present directory. Output of "ls -al" used as input to grep command.

Monday, March 4, 2013

basic commands you must know in linux

A small list of Linux commands which every one must know in order to work on console :

1. cd - change directory.
2. cd .. - go one directory level back.
3. pwd - present working directory.
4. rm - remove / delete a file. "rm <file>"
5. rm -r - recursively remove a directory.
6. cp - copy a file " cp<source> <destination>"
7. mv - move similar to cut in windows. "mv <source> <destination>"
8. cat - display contents of a file. "cat <file>"
9. grep - search string in a file. Used with pipe(|). "cat <file> | grep <string> " or. "grep <string> <file>
10. find - find a file in a directory. "find ./ -name <file>"
11. top - to monitor activities running on your system.
12. ls - list contents of a directory.
13. ps - show processes running on present console.
14. rlogin - remote login to server. "rlogin <server-name>"
15. ssh - open a secure shell to other server. "ssh <server-name>"
16 scp - secure copy to other server. "scp <file-name> <server-name>"
17. tar - to create a tar file. compressing a folder.
18. vi/vim/gvim - open file in code editors like vi,vim,gvim.
19. gedit - open file in gedit. "gedit <file>"
20. gcc - compile C code "gcc <file.c>". produces a.out.
21 ./<executable> - run the executable or script file.
22. chmod - change access mode of a file or directory. "777" sets it to all read, all write and all run.

Wednesday, June 20, 2012

GVIM BASICS & TIP & TRICKS -2 short tutorial

This article is in continuation from my last article gvim-basics-tip-tricks-1. The best thing with GVIM is that each day you get to learn something new and useful to learn.

So more tips and tricks:
1) * : "*" is used to search word near/under your cursor.

2) %: "%" can be used to look for accompanying bracket. {},[],(). For example if your cursor is on "{" and you press "%" the it will take you to the corresponding "}". It can be very useful when used with "d"(delete) or "y"(yank).

3)"q:"- "q:" is used to view your command history, you can copy paste commands from there or even edit the commands and run the commands directly by selecting them.

4)"q/" - used view previous searches.

5) If you like colors then you can put on the color font by ":syntax on" or just put "syntax on" in your .vimrc file and this action will be taken every time you open a new vim window.

6) w! - sometimes when you try to edit write protected file ":w!" can be useful .

7) :wq! - save and exit write protected file.

I will share some tips and tricks here and keep on writing new articles as I learn more.

Friday, June 15, 2012

GVIM BASICS & TIP & TRICKS -1 short tutorial

As I mentioned in my last post I have been working on GVIM for past few months and each day I am surprised by some new capabilities of the tool. I will share some tips and tricks here and keep on writing new articles as i learn more.

Some basics:

1) Save your file with ":w"
2) Exit with ":q"
3) Start writing/inserting text : "i"
4) copy a line: "y"
5) paste the copied line : "p"
6) Save and exit with ":wq"
7) Undo : "u"
8) Redo: "ctrl+r"
9) Search:  use "?" or "/" followed by string to search use "n" for next match.
10) Replace: use ":%s/str1/str2/g" to replace str1 to str2 globally ":%s/str1/str2/gc" will confirm before replacing.
11) To add "tab" before each line select the lines and then press">".
12) ":g/str/g": This command will delete the lines containing string "str"
13) To display line numbers : ":set nu"
14) To turn of display of line numbers : ":set nu!"
15) ":help" : To open help file.
16) ":set ic" :  after this command all the searches will be case insensitive.
17) ":set noic" : after this command all the searches will be case sensitive.

Tricks:
1) In all the command when you give strings and if your string contains special characters (#$@^&\/) then just add "\" befor the special character.
eg: in order to search for "a/b/c" the command should be "/\/a\/b\/c"

2) you can have a .gvimrc file in your home directory in which you can write all the set commands like ":set nu" and all the other commands listed up. GVIM will read the file every-time it starts and will apply the settings.

3) Type "/" and keep on pressing ctrl+p to find what was your previous searches.

4) If you want to delete next 10 lines, then in normal mode type "10dd", for 5 -"5dd"  so trick is <number>dd, same can be done for yank(copy) "<number>yy"

Saturday, June 9, 2012

HOW "VIM" IS THE KING OF ALL IDE's

I used "source insight" for more than 15 months and I just loved the tool and just cannot imagine writing a code without it but then my life changed a little bit and I have to start working on a red hat machine so no source insight.

At start I found it to be very difficult to survive without it but later on doing some search over Internet I found some tools which can save my life while coding on Linux . Some of those life saver tools were cscope, Ctags, etc but the tool on which all these work the king of all Vi/VIM/GVIM. After 6 months of work on gvim now I no longer miss source insight.

The learning curve on vim is quite steep there are loads of stuff you can do on it which you a cannot think of doing on any other IDE. The Internet is full with the tutorials and tips and tricks for these tools. It just took me few weeks to be comfortable with them and use them flawlessly.

So I think I will write an article on tips and tricks I use on vim a collection of all the tricks I accumulate in last 5-6 months. Will try to do that in coming days keep looking for that in this space.


A word of caution for all those who are looking forward to using these awesome tools they are very addictive. Nowadays even when I try to save my MS word doc I try to do it with ":w"(all those who use vim will get the joke ;) )........


Do leave comments about how you feel about these wonderful tools ... Thanks

Monday, May 7, 2012

Replacement for source insight in Linux

Few days back I changed my job. In my last job I used to work on windows machine and used source insight as my default IDE. In my new job I work on Red hat machine so have no "source insight". First few days I spent on google to find a replacement . So I think it's a good idea to share all the information I got....

1) cscope : a nice tool for exploring large codes ... You just need to save all the files in the project to the file "cscope.files" ... To do this run the following command at the to directory of your code base :
"find ./ -name "*.c">cscope.files"
"find ./ -name "*.h">>cscope.files"
....
And similar command for all the file extension you have in your project .

Finally type command "cscope" and you are ready to go ... It will show you options like find C symbol ,global definition ,find string,replace string, ... And a few more .. Although it is not a complete replacement for "source insight" but you get used to it in long run ..

2) Ctags/tags : this option can be used with vim just prepare the tags file and there you go now of you want to jump to definition of any function/variable/constant/structure .. Just keep cursor over the function and press cntrl+t .. Press cntrl+] to return .. If you are using GVIM then its even more simple   . press cntrl+left-click to go to tag press cntrl+right-click to return.

3) use Eclipse ... Although I have not personally used it but have heard that they have a package for Linux also ..

4) finally if you know the code well and do not need frequent searching .. Then you can survive with emacs/vi/vim/gvim. Actually these are one of the best IDE's if you can master them. Learning curve for vim is quite steep and same goes with emacs. All i can say is that these are very powerful tools only in the right hands. There are a loads of stuff you can do with these tools quite easily which you cannot think of doing with other IDE's.


If you are working on Linux and use different IDE for code browsing ..comments are most welcome

Sunday, May 6, 2012

finding text in files linux

Using grep for finding some text in group of files can be sometimes complex specially when u have a directory with multiple hierarchy .. currently while looking for some simple option i found this command :
"find . |xargs grep "your_txt""
if you want to find the text in only .C files then also its simple use command:


"find ./ -name "*.C" |xargs grep "your_txt""

such use of find and grep together with xargs can make life simple many times.