Friday, 14 September 2018

Commands & tool for working in C environment


Cscope

·         find . -name "*.c" -o -name "*.cpp" -o -name "*.h" -o -name "*.xml" -o -name "Makefile" -name "makefile" > cscope.files

·         cscope -q -R -b -i cscope.files

·         ctags -L cscope.files   -> this is working.



Vim:

·         To move next line based on previous line

o    Set cintend

·         To highlight the white space

/\s\+$

:set hlsearch

Or  

:match Error /\s\+$/

·         To count the selected word

o    :%s/pattern//gn

·         Replance from current cursor position:

o    .,$s/conn/connLow/gc     => "."  is considered as the current position.



·         Diff in the console with | symbol to notify diff, not vimdiff, tool is diff

o    diff -y summary.txt -y output/summary.txt

·         Control+W followed by W to toggle between open windows and,



Notepad ++:

·         Short cut for go to specific line

o    Ctrl + g

o    To block select like VIM, similar to ctrl + v in VIM

o    ctrl + alt + shift and then left click mouse





Coverity:

1.       Coverity line between 2 diff with duplicate lines

Replace branch name in another file

sort tmp_857 | uniq -c > sort_tmp_857

sort tmp_fresh | uniq -c > sort_temp_fresh

vimdiff sort_tmp_fresh  sort_tmp_857


Find:

·         To list the extention of file from this path

o    find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u



·         To list specific file

o    find -regex ".*\.\(jpg\|gif\|png\|jpeg\)"





Grep:

·         To display a multiple pattern

grep -E 'foo|bar' *.txt

EG: Top command to display 2 var=> top | grep -E 'Mem|CPU|tcpdump|Load'

·         To search backslash

grep -r \\\\ *

·         To list only the file name

grep -l

·         To display the next 3 line from the founded word

grep -A 3 FORWARD_NULL folder_name_857.txt

·         To display line before & After

o    grep's -A 1 option will give you one line after;

o    -B 1 will give you one line before;

o     -C 1combines both to give you one line both before and after.

·         To search only header files:

o    grep -ri --include \*.h *





X11 -> display

Xauth list -> to list the authenticate cookies



Below command to remove all entries in xauth to resolve "X11 proxy: MIT-MAGIC-COOKIE-1 data did not matchError" Error

 xauth list | cut -f1 -d\  | xargs -i xauth remove {}



LS:

To list the KB or MB

Ls --block-size=k for KB,

Ls --block-size=m for MB.



Other Unix command:

·         To list the file details

file -L /usr/lib/libpcap.so.1

·         du -sh * => will display the all folder with used size

·         du -sh * | sort -h   ==> to sort in order.

·         lsb_release -a => to know the Ubuntu version(Eg: 14.0)

·         Convert Linux txt file into windows format:

o     perl -p -e 's/\n/\r\n/' < test > dosfile3.txt

·         Empty the contents of a file:

o    cp /dev/null <file Name to empty>

·         Remove the stray value " error: stray ‘\302’ in program" or error: stray ‘\240’ in program from .c file.

o    tr -cd '\11\12\15\40-\176' < old.c > new.c

·         Unzip the file:

o    Run file access-2.log.gz, it will tell you the compression type.

·         EG: $file tmp.gz

         tmp.gz: 8086 relocatable (Microsoft)

·         To know the default gateway

ip route | grep default

·         To know the DNS is resolving or not

o    nslookup google.com   => It should return the google.com ip

·         Iptables & conntrack

o    To list the conntrack entries

·         conntrack –L

·         conntrack -L -p tcp --dport 80

o    To delete the entries in conntrack

·         conntrack -D

o    To delete Input rule

·         iptables -L -n -v --line-number

·         iptables -D INPUT 3

o    To delete POSTROUTING:

·         iptables -t nat -L -n -v --line-number

·         iptables -t nat -D POSTROUTING 2

o    Command to list:

·         iptables -L

·         iptables -L -n  => For INPUT, FORWARD and OUTPUT-chains

·         iptables -L -t nat

·         iptables -t nat -L -n -v  -> to View nat rules



Screen:

          screen -S <user name> => To create a new screen.

screen -x <name>   => To open an existing screen.

screen -ls    => To list the available screen

ctrl + a+c   => to create a new window inside the screen.

ctrl +a + d  => To come out from the screen.

Ctrl + a + A  => To rename the current window.

F1      => move backside window inside the screen

F2      => Move forward window inside the screen.

Screen -L -x <name >   => Open the session with saving the logs in home dir.





Tools:

Ss->  socket statistics.

netstat command reads various /proc files but ss gets its information directly from kernel space, so good.

ss -ap | grep high => give the ipc socket details with process id.

-u => udp   (IPC socket is not udp because it don’t have any layer 3 IP)

-t => tcp

-a => all

Visio -> is a tool for msoffice to use UML diagram.

nm -> to find the function name in binary =>  nm -A nsh  | grep nsh_sdb_connect

Objdump -> used to find function name but our ARM architecture not supporting.

arm-elf-objdump -> not installed

arm-elf-objdump -D -b binary -marm binaryfile.dat



Ldd:

You can list the shared library dependencies which your executable is dependent

abuser@labuser-virtual-machine:~/velrajk/sample/ipc_soc/API$ ldd cli

        linux-vdso.so.1 =>  (0x00007ffd4d38e000)

        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f6c03f7b000)

        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6c03bb3000)

        /lib64/ld-linux-x86-64.so.2 (0x00007f6c04199000)

labuser@labuser-virtual-machine:~/velrajk/sample/ipc_soc/API$



·         Wing ftp:

o    It’s a trial software supports ftps server.

o    Create new domin &  new user, give the ftp directory path while creating user.

o    Domain is the FTP server or HTTP server running port

o    User is the ftp login username, while connecting to this ftp need to give this user details for login.

o    Windows defender firewall or any firewall on windows PC should be disabled.







Linux troubleshoot:

Firefox not opening:

sudo chown labuser:labuser .Xau*

rm .Xauthority-c

rm .Xauthority-1


Thursday, 13 September 2018

count character, line & word in the file using c program

Note:
  •  For getchar should not use char datatype, because it may return EOF.
  • The value for EOF is -1

Program:

#include <stdio.h>
#include <errno.h>

#define WORD_OUTSIDE 1   /* Word outside */
#define WORD_INSIDE  0   /* Word inside  */

int main(int argc, char *argv[])
{
        /* For getchar should not use char datatype, because it return EOF.
         * The value for EOF is . */
        int   ch = 0, nc = 0, nl = 0, nw = 0, word_in_out;
        FILE  *fp_input = NULL;

        if (argc <=1) {
                printf("Give file name in the command prompt while executing the commmand: \n\n");
                return 0;
        }

        fp_input = fopen(argv[1], "r");
        if (fp_input == NULL) {
                printf("Failed to open the file %d. \n\n", errno);

                perror("Error:");
                return 0;
        }

       word_in_out = WORD_OUTSIDE;
        while ((ch = fgetc(fp_input)) != EOF) {
                ++nc;
                if (ch == '\n') {
                        ++nl;
                }
                if ((ch == ' ') || (ch == '\n') || (ch == '\t')) {
                        word_in_out = WORD_OUTSIDE;
                } else if (word_in_out == WORD_OUTSIDE) {
                        ++nw;
                        word_in_out = WORD_INSIDE;
                }
        }

        printf("Total number of character = %d, Line = %d, word = %d \n",
                       nc, nl, nw);

        return 0;
}

Output:

velraj@velraj-HEC41:~/CProgram$ ./a.out new
Total number of character = 28, Line = 5, word = 7

Tuesday, 4 September 2018

Linked list add, delete & display


Program:


#include <stdio.h>
#include <stdlib.h> // for calloc

typedef struct node {
    struct node *next;
    int value;
}node_t;

node_t *root = NULL;

void line_80(char *str)
{
    int i;
    for (i = 0; i < 80; printf("%s", str), i++);
    printf("\n");
}

void display_list(void)
{
    node_t *temp = NULL;
    if (root == NULL) {
        printf("List is empty \n");
    }
    printf("\tThe available list value is: ");
    for (temp = root; temp ; temp = temp->next) {
        printf("%d ", temp->value);
        if (temp->next) {
            printf("-> ");
        }
    }
    printf("\n\n");
}

int insert_list(node_t  **root_node, int value)
{
    node_t  *temp = NULL;
    temp = (node_t *) calloc(1, sizeof(node_t));
    temp->value = value;
    if (*root_node == NULL) {
        *root_node = temp;
    } else {
        temp->next = *root_node;
        *root_node = temp;
    }
}
void delete_list(node_t **root_node, int value)
{
    node_t *temp = NULL, *prev = NULL;
    if (*root_node == NULL) {
        printf("List is empty, so could not delete any value \n");
        return;
    }
    for (temp = prev = *root_node; temp ; prev = temp, temp = temp->next) {
        if (temp->value == value) {
            if (temp == *root_node) {
                *root_node = temp->next;
            } else {
                prev->next = temp->next;
            }
            free(temp);
            temp = NULL;
            printf("Delete the node with value %d \n", value);
            return;
        }
    }
}

int main()
{
    int input, choice = 0, value = 0;

    while (1) {
        line_80("*");
        printf("\t 1. Display the list\n\t 2. Insert to list: \n\t 3.Delete from list\n");
        line_80("*");
        printf("\n\t Enter your choice: ");
        scanf("%d", &choice);
        if (choice <= 0 || choice >= 4) {
            printf("Please choose correct choice \n");
            continue;
        }
        switch(choice)
        {
            case 1:
                display_list();
            break;
            case 2:
                printf("Enter the value to insert:");
                scanf("%d", &value);
                insert_list(&root, value);
            break;
            case 3:
                printf("Enter the value to delete:");
                scanf("%d", &value);
                delete_list(&root, value);
            break;
            default:
                printf("Wrong choice, select correct choice \n");
        }
    }
}



Output:


learn$ ./a.out
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 1
List is empty
        The available list value is:

********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 2
Enter the value to insert:1
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 2
Enter the value to insert:2
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 2
Enter the value to insert:3
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 1
        The available list value is: 3 -> 2 -> 1

********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 3
Enter the value to delete:2
Delete the node with value 2
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 1
        The available list value is: 3 -> 1

********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 3
Enter the value to delete:1
Delete the node with value 1
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 1
        The available list value is: 3

********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 3
Enter the value to delete:3
Delete the node with value 3
********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************

         Enter your choice: 1
List is empty
        The available list value is:

********************************************************************************
         1. Display the list
         2. Insert to list:
         3.Delete from list
********************************************************************************


Saturday, 25 August 2018

Data type of pid_t is int


  • /sys/types.h
    • #ifndef __pid_t_defined
      typedef __pid_t pid_t;
      # define __pid_t_defined
      #endif
  • bits/types.h
    •  __STD_TYPE __PID_T_TYPE __pid_t;        /* Type of process identifications.  */# #define __STD_TYPE             typedef
    • #define __PID_T_TYPE            __S32_TYPE
    • #define __S32_TYPE              int

Wednesday, 1 August 2018

Strncmp usage from working



SYNOPSIS

#include <string.h>
 int strncmp(const char *s1, const char *s2, size_t n);

Description
The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2.

RETURN VALUE
       The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively,  to  be  less  than,  to
       match, or be greater than s2.

  • strncmp will be usefully only if the both strings are not null terminated, at that time only it will be useful to stop the comparison upto n.
  • if we are using strlen to calculate lenght to give on  n, then strncmp is not useful.
  • strncmp with strlen is as good as strcmp.
  • Right way to use strncmp is to check for max allowed lenght.  we can use max size macro used to declare the string.

Wednesday, 27 June 2018

Convert Error no(errno) into a string value

NAME

       strerror, strerror_r - return string describing error number

SYNOPSIS

 #include <string.h>
       char *strerror(int errnum);
       int strerror_r(int errnum, char *buf, size_t buflen);
                   /* XSI-compliant */
       char *strerror_r(int errnum, char *buf, size_t buflen);
                   /* GNU-specific */
   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
       The XSI-compliant version of strerror_r() is provided if:
       (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
       Otherwise, the GNU-specific version is provided.
     

DESCRIPTION


  • The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum.
    • For example, if errnum is EINVAL, the returned description will "Invalid argument".
  • This string must not be modified by the application, but may be modified by a subsequent call to strerror()
  • The  strerror_r()  function  is  similar to strerror(), but is thread safe. 

RETURN VALUE

    Return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.

Program:

/* error number into an String value program by Velraj.K
   Check : http://velrajcoding.blogspot.in
  */


#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
    FILE *fp;

    /* first rename if there is any file */
    rename("file.txt", "newfile.txt");

    /* now let's try to open same file */
    fp = fopen("file.txt", "r");
    if( fp == NULL ) {
        perror("Error: ");
        printf("velraj errno = %d value (%s)\n", errno, strerror(errno));
        return(-1);
    }
    fclose(fp);

    return(0);

}

Output:

sample$ ./a.out
Error: : No such file or directory
velraj errno = 2 value (No such file or directory)


Tuesday, 26 June 2018

python - Split the file name from git diff


Program:

import sys   # For command line argument
import os.path # To check file existing

def generate_writefile(file_name):
    count = 1
    while True:                      # in True T must be capital
        file_name_new = file_name
        file_name_new += "_" + str(count)
        count += 1
        if not os.path.isfile(file_name_new):
            return file_name_new
        if count >=10 :
            print "Error while creating file"
            return None


def main():
    cmd_len = len(sys.argv)
    if(cmd_len <2):
        print "\t\tVel Error, provide the git file name\n\n"
        return

    name =  sys.argv[1]
    file_name = generate_writefile(sys.argv[1])
    if file_name == None:
        return
    file_write = open(file_name, 'w')
    if  not os.path.isfile(sys.argv[1]):
        print "Vel Error, provided file is not existing\n\n"
        return

    count_file = 0
    with open(sys.argv[1]) as openfileobject:
        for line in openfileobject:
            spl_for_com = line.split()      # convert the list of array into an separated string
            length = len(spl_for_com)
            if((length >=4) and (spl_for_com[0] == "diff") and (spl_for_com[1] == "--git")):
#        print "Got the match velraj ", spl_for_com[2][1:], spl_for_com[3]
                file_write.write(spl_for_com[2][1:])
                file_write.write("\n")
                count_file += 1
    print "Number of file = ", str(count_file), "Output file name is = ", file_name

    if count_file == 0:
        os.remove(file_name)

main()


# API to read from file.
    #    message = file_read.read()   # It read a whole file in  1 time
    #    message = file_read.readline()  # Its read only single line