Friday, 18 May 2018

Get the currently process priority & scheduling policy & priority, also change the priority

Get the currently process priority & scheduling policy & priority, also change the priority

API Description:

 #include <sched.h>
       int sched_get_priority_max(int policy);
       int sched_get_priority_min(int policy);
  • sched_get_priority_max() returns the maximum priority value that can be used with the scheduling algorithm identified by policy.
  • sched_get_priority_min() returns the minimum priority value that can be used with the scheduling algorithm identified by policy.

 #include <sched.h>

       int sched_setscheduler(pid_t pid, int policy, const struct sched_param *param);
       int sched_getscheduler(pid_t pid);

  • The sched_setscheduler() system call sets both the scheduling policy and parameters for the thread whose ID is specified in pid.
  • If pid equals zero, the scheduling policy and parameters of the calling thread will be set.


#include <sys/time.h>
#include <sys/resource.h>
             int getpriority(int which, int who);
            int setpriority(int which, int who, int prio);
  • The scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority() call and set with the setpriority() call.
  • The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER).
  • A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.

  • Prio is a value in the range -20 to 19 (but see the Notes below). The default priority is 0; lower priorities cause more favorable scheduling.

#include <sched.h>
      int sched_setparam(pid_t pid, const struct sched_param *param);
      int sched_getparam(pid_t pid, struct sched_param *param);

struct sched_param {
    ...
    int sched_priority;
    ...
};
  • sched_setparam() sets the scheduling parameters associated with the scheduling policy for the process identified by pid. If pid is zero, then the parameters of the calling process are set.


Program:


#include <stdio.h>
#include <sched.h>   // sched_getscheduler & set

/* For getpriority & setpriority */
#include <sys/time.h>
#include <sys/resource.h>

#include <errno.h>   // For errno
#include <stdlib.h>   // For exit
#include <string.h>  // for memset

const static int SCHED_POLICY_MAX = 3;
const char *sched_policies[] = {
    "SCHED_OTHER",
    "SCHED_FIFO",
    "SCHED_RR",
    "SCHED_BATCH"
};

int print_sched_type(pid_t pid)
{
    int policy = sched_getscheduler(pid);
    if (policy < 0) {
        perror("Syscall sched_getscheduler() had problems");
        return -1;
    }
    if (policy > SCHED_POLICY_MAX) {
        printf("Syscall sched_getscheduler() returned a policy number greater than allowed!\n");
        return -1;
    }
    printf("The current scheduling policy is: %s\n", sched_policies[policy]);
 
void print_process_prio(pid_t pid)
{
    /* Get the proirity of this process. This is the NON-REALTIME priority.
     *   http://linux.die.net/man/2/getpriority
     */
    /* This can return -1 as a legitimate value, so first clear errno
     * and make sure to check it after the call.
     */
    errno = 0;
    int this_prio = getpriority(PRIO_PROCESS, pid);

    if ((this_prio == -1) && (errno)) {
        perror("Syscall getpriority failed");
    } else {
        printf("Process priority is: %i\n", this_prio);
    }
}

void print_sched_priority(pid_t pid)
{
    /* Get and inspect the scheduling parameters.  This can contain realtime relevant
     * information if this process is operating with SCHED_FIFO
     */
    struct sched_param param;

    if (sched_getparam(pid, &param) < 0) {
        perror("Syscall sched_getparam barfed");
    } else {
        printf("The sched_param schedule priority is: %i\n", param.sched_priority);
    }
}

void hline(void)
{
    char str[82];
    memset(str, '-', 80);
    str[80] = '\n';
    str[81] = '\0';
    printf("%s", str);
}

int main(int argc, char *argv[])
{
    int policy = -1;

    /* Get the maximum schedule priority
http://linux.die.net/man/2/sched_get_priority_max
     */
    int max_prio_FIFO = sched_get_priority_max(SCHED_FIFO);
    int max_prio_RR = sched_get_priority_max(SCHED_RR);
    int max_prio_OTHER = sched_get_priority_max(SCHED_OTHER);

    printf("Scheduling Priority Maximums:\n"
            "    SCHED_FIFO: %i\n"
            "    SCHED_RR: %i\n"
            "    SCHED_OTHER: %i\n",
            max_prio_FIFO,
            max_prio_RR,
            max_prio_OTHER);

    /* Get the minimum schedule priorities for each process scheduling type
     *  http://linux.die.net/man/2/sched_get_priority_min
     */
    int min_prio_FIFO = sched_get_priority_min(SCHED_FIFO);
    int min_prio_RR = sched_get_priority_min(SCHED_RR);
    int min_prio_OTHER = sched_get_priority_min(SCHED_OTHER);
   printf("Scheduling Priority Minimums:\n"
            "    SCHED_FIFO: %i\n"
            "    SCHED_RR: %i\n"
            "    SCHED_OTHER: %i\n",
            min_prio_FIFO,
            min_prio_RR,
            min_prio_OTHER);

    print_process_prio(0);
    print_sched_priority(0);
    policy = print_sched_type(0);    // If we run on ubuntu getting default proces schedule is "Other"

    hline();


    /* Need to run from root user if we need to change the process priroty,
       otherwise it will thrown on error */
    printf("Attempting to switch process to SCHED_FIFO...\n");
    struct sched_param sp;
    memset(&sp, 0, sizeof(sp));
    sp.sched_priority = 50; /* This cannot be higher than max_prio_FIFO! */
    if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
        perror("Problem setting scheduling policy to SCHED_FIFO (probably need rtprio rule in /etc/security/limits.conf)");
        exit(1);
    }

    print_process_prio(0);
    print_sched_priority(0);
    print_sched_type(0);

    printf("\nTest completed successfully!\n");
}

Output without Root permission:

sample$ ./a.out
Scheduling Priority Maximums:
    SCHED_FIFO: 99
    SCHED_RR: 99
    SCHED_OTHER: 0
Scheduling Priority Minimums:
    SCHED_FIFO: 1
    SCHED_RR: 1
    SCHED_OTHER: 0
Process priority is: 0
The sched_param schedule priority is: 0
The current scheduling policy is: SCHED_OTHER
--------------------------------------------------------------------------------
Attempting to switch process to SCHED_FIFO...
Problem setting scheduling policy to SCHED_FIFO (probably need rtprio rule in /etc/security/limits.conf): Operation not permitted

Output with Root permission:

labuser@labuser-virtual-machine:~/velrajk/sample$ sudo ./a.out
[sudo] password for labuser:
Scheduling Priority Maximums:
    SCHED_FIFO: 99
    SCHED_RR: 99
    SCHED_OTHER: 0
Scheduling Priority Minimums:
    SCHED_FIFO: 1
    SCHED_RR: 1
    SCHED_OTHER: 0
Process priority is: 0
The sched_param schedule priority is: 0
The current scheduling policy is: SCHED_OTHER
--------------------------------------------------------------------------------
Attempting to switch process to SCHED_FIFO...
Process priority is: 0
The sched_param schedule priority is: 50
The current scheduling policy is: SCHED_FIFO

Test completed successfully!




Saturday, 12 May 2018

Bitwise Operator


Bit Operator


| – Bitwise OR
& – Bitwise AND
~ – One’s complement
^ – Bitwise XOR
<< – left shift
>> – right shift


Bitwise OR – |


   1010
   1100
   -------
OR 1110 
   -------
 

Bitwise AND – &


    1010
    1100
    -------
AND 1000   
    -------


One’s Complement operator – ~


       1001
NOT
      -------
       0110
      -------

 

Bitwise XOR – ^


     0101
     0110
     ------
XOR  0011
     ------


 

Left shift Operator – <<

int a=2<<1;

Position  7    6    5    4    3    2    1    0
Bits      0    0    0    0    0    0    1    0

after 1 time shift:

Position  7    6    5    4    3    2    1    0
Bits      0    0    0    0    0    1    0    0

 

Right shift Operator – >>

========================

int a=8>>1;

Position    7    6    5    4    3    2    1    0
Bits        0    0    0    0    1    0    0    0


after 1 right shift:

Position   7    6    5    4    3    2    1    0
Bits      0     0    0    0    0    1    0    0

 

Note on shifting signed and unsigned numbers

============================================

While performing shifting, if the operand is a signed value, then arithmetic shift will be used. If the type is unsigned, then logical shift will be used.

In case of arithmetic shift, the sign-bit ( MSB ) is preserved. Logical shift will not preserve the signed bit. Let’s see this via an example.


int main() {
    signed char a=-8;
    signed char b= a >> 1;
    printf("%d\n",b);
}


In the above code, we are right shifting -8 by 1. The result will be “-4”. Here arithmetic shift is applied since the operand is a signed value.




Now unsigned shift:

int main() {
    unsigned char a=-8;
    unsigned char b= a >> 1;
    printf("%d\n",b);
}


Note: Negative number are represented using 2’s complement of its positive equivalent.


2's compliment of +8 is
          8 = 0000 1000
1st complit = 1111 0111
2's compli  = 1111 1000

1111 1000

Right shifting by 1 yields, 0111 1100 ( 124 in decimal )

Hence we will get the positive 124 value:


 

Toggle a bit:

============
value = data ^ (1 << n)

Input data is 8
Bit needs to be toggled is 2.

   value = (0000 1000) ^ (0000 0001 << 2)
         = (0000 1000) ^ (0000 0100) => (0000 1100) = 12




 

Tricks:

********

Get the maximum integer

int maxInt = ~(1 << 31);
int maxInt = (1 << 31) - 1;
int maxInt = (1 << -1) - 1;

 

Get the minimum integer

int minInt = 1 << 31;
int minInt = 1 << -1;

 

Get the maximum long

long maxLong = ((long)1 << 127) - 1;

 

Multiplied by 2

n << 1; // n*2

 

Divided by 2

n >> 1; // n/2

 

Multiplied by the m-th power of 2

n << m;

 

Divided by the m-th power of 2

n >> m;

 

Check odd number

(n & 1) == 1;


Exchange two values

a ^= b;
b ^= a;
a ^= b;

Thursday, 26 April 2018

python - The message packer reads a string

The message packer reads a string

You need to implement a Message Packer. The message packer reads a string

Rules:

  • adds two chars ZZ to mark the beginning of the message
  • add number 0 to mark the end of the message.
  • The input string is reversed inside the message.
  • If the input string contains char Z then it is replaced by # in the message. The lower case character z is retained
  • If the input string contains numeric character 0 then it is replaced by $.
  • Only lower case letter ([a-z]), upper case letter ([A-Z]) and numeric characters ([0-9]) are accepted. If the string contains any other characters an error message Invalid String
  • Maximum number of characters accepted in the string is 8. If the number exceeds 8 then Exceeded Limit   is output

Sample:

  • Input : You need to read a string from STDIN.
  • Output :  Message Packed as per rules above or Invalid String or Exceeded Limit is  printed.

  • Input: PQRS
  • Output: ZZSRQP0

  • Input: ABbcZdz
  • Output: ZZzd#cbBA0

  • Input: X1340yZ
  • Output: ZZ#y$431X0

  • Input: AB*D1$34
  • Output: Invalid String

  • Input: ABCD12345
  • Output: Exceeded Limit

Program:

def main():
    message = raw_input("Enter value :")

    count = 0
    reverse = ''.join(reversed(message))    # Reversed the string , must need join

    lis = list(reverse)          # Reverse the string

    lengh = len(reverse)
    if lengh > 8:                # Length should be less than 8
        print "Exceeded Limit"
        return

    count = 0
    for char in lis:
        if char == 'Z':
            lis[count] = '#'
        elif char == '0':
            lis[count] = '$'
        elif not (char.isupper() or char.islower() or char.isdigit()):
            print "Invalid String"
            return
        count = count + 1

    lis.append('0')
    lis = ['Z'] + lis                 # Append the Z to the begging of the list
    lis = ['Z'] + lis

    result = ''.join(lis)            # Convert list to the string

    print result

main()

Output:

acp_python$ python messagePacker.py
Enter value :ABbcZdz
ZZzd#cbBA0
acp_python$ vi messagePacker.py
acp_python$ python messagePacker.py
Enter value :X1340yZ
ZZ#y$431X0
acp_python$ python messagePacker.py
Enter value :AB*D1$34
Invalid String
acp_python$ python messagePacker.py
Enter value :ABCD12345
Exceeded Limit

python - Password validity checker using python

Password validity checker using python


  • You need to implement a password validity checker.  A password is valid if all the given rules are satisfied, else it is invalid.
    •  At least 1 (one) lower case letter ([a-z]) is present
    •  At least 1 numeric character ([0-9]) is present  
    •  At least 1 (one) upper  case letter ([A-Z]) is present
    •  At least 1 character from [$#@] is present
    •  Minimum and Maximum length allowed must be 6 and 12 respectively
  • Input : You need to read a string from STDIN and check if it is a valid or invalid password.
  • Output : The string valid or invalid printed.

  • Test Cases:

    • Input: ABCDa$$$$$56
    • Output: valid

    • Input: 12345abcd111
    • Output: invalid
    • Input: 2w3E*
    • Output: invalid

Program:

def main():
    password = raw_input("Enter value :")

    digit = 0
    upper = 0
    lower = 0
    special = 0
    flag_len = 0

    for char in password:
        if char.isdigit():
            digit = 1
        if char.isupper():
            upper = 1
        if char.islower():
            lower = 1
        if char == '$' or  char == '#' or char == '@':
            special = 1

    length = len(password)
    if length >= 6 and length <= 12:
        flag_len = 1

    if digit and upper and lower and special and flag_len:
       print "valid"
    else:
       print "invalid"

main()


Output:

python$ python passwordVali.py
Enter value :Velraj
invalid
python$
python$
python$ python passwordVali.py
Enter value :Velraj12#
valid

Monday, 23 April 2018

how to run system command in c

how to run system command in c

  • Use system( ) to run the command if input and output are not important.
  • Use popen( ) if control on either input or output is needed.

System:

  • system() is used to invoke an operating system command from a C/C++ program.
  • int system(const char *command);
    • stdlib.h  is needed

  • Using system(), we can execute any command that can run on terminal if operating system allows. 
  • For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.

Example Program:

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

int main () {
    char command[256];

    strcpy( command, "ls -l" );
    system(command);
   
    return 0;
}

Output:

sample$ ./a.out
total 156
-rw-rw-r-- 1 labuser labuser     159 Dec 18 21:59 '
-rw-rw-r-- 1 labuser labuser     338 Aug  3  2017 ]
-rw-rw-r-- 1 labuser labuser    1035 May 16  2017 access.c
-rwxrwxr-x 1 labuser labuser    8688 Apr 23 21:52 a.out
-rw-rw-r-- 1 labuser labuser     231 May 16  2017 array_init.c
-rw-rw-r-- 1 labuser labuser     585 May 19  2017 array_size.c
-rw-rw-r-- 1 labuser labuser     347 Aug 30  2017 assert.c
-rw-rw-r-- 1 labuser labuser     992 Jan 31 21:14 backtrace.c


Friday, 6 April 2018

How to use gprof to generate gmon.out while running the program

How to use gprof to generate gmon.out while running the program

  • The function "monstartup" is used to reinitialize the data block used by gmon to collect profile data.
  • The function "_mcleanup"  writes profile data to gmon.out
  • Change the current direct to /tmp to place the gmon.out to the default folder /tmop
  • After finish the test revert the current folder.
  • Send the SIGUSR2  signal to the process to generate the gmon.out file.
  • Generate the gmon.out file
    • send the signal using below
      • $kill -s SIGUSR2 26908
  • See the output in below folder
    • $cd /tmp

Example Program:

Program file 1: gprof_test-signal.c

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


#include <dirent.h>
#include <sys/gmon.h>
#include <signal.h>
#include <string.h>

void write_gmon_out_file();
void sigusr2_handler(int sig);
void gprof_init(void);

/* Beginning and end of our code segment.  */
extern void _start (void), etext (void);

/*
 * This function uses APIs from the gmon library which is part of the
 * the standard glibC library, to force write the profile data.
 * The function "monstartup" is used to reinitialize the data block
 * used by gmon to collect profile data.
 * The function "_mcleanup"  writes profile data to gmon.out
 */
void write_gmon_out_file (void)
{
    char *gmon_dir = "/tmp";
    char originalDir[256];

    if (getcwd(originalDir, 256) == '\0') {
        printf("Failed to get original working directory... \n");
        memset(originalDir, 0, 256);
    }
    else {
        printf("Original Dir = %s \n", originalDir);
    }

    if (chdir(gmon_dir) == 0) {
        printf("Successfully changed to dir = %s \n", gmon_dir);
    }
    else {
        printf("Failed to change to dir = %s \n", gmon_dir);
    }

    _mcleanup();
    monstartup((unsigned long ) &_start, (unsigned long ) &etext);

    if (originalDir[0] != 0) {
        printf("Switching to original working dir ...\n");
        chdir(originalDir);
    }

    return ;
}

void sigusr2_handler(int sig)
{
    printf("Received Signal: %d\n", sig);
    write_gmon_out_file() ;
    signal(SIGUSR2, sigusr2_handler) ;
}
void gprof_init(void)
{
    signal(SIGUSR2, sigusr2_handler) ;
    printf("GPROF SIGNAL HANDLER INITIALIZED\r\n");
    sleep(5);
}
void new_func1(void);

void func1(void)
{
    printf("\n Inside func1 \n");
    int i = 0;

    //exit(0);
    sleep(10);
    for(;i<0xffffffff;i++);
    new_func1();

    return;
}

static void func2(void)
{
    printf("\n Inside func2 \n");
    int i = 0;

    for(;i<0xffffffaa;i++);
    return;
}

int main(void)
{
    printf("\n Inside main()\n");
    int i = 0;

     gprof_init();
    for(;i<0xffffff;i++);
    func1();
    func2();

    return 0;
}

Program 2: gprof_test_2.c

//test_gprof_new.c
#include<stdio.h>

void new_func1(void)
{
    printf("\n Inside new_func1()\n");
    int i = 0;

    for(;i<0xffffffee;i++);

    return;
}

Output:

Execute the program:
gprof$ ./a.out

 Inside main()
GPROF SIGNAL HANDLER INITIALIZED

 Inside func1

Received Signal: 12
Original Dir = /home/labuser/velrajk/sample/gprof
Successfully changed to dir = /tmp
Switching to original working dir ...

---- output file.
$cd /tmp
$ ls gmon.out 
gmon.out
$

Friday, 30 March 2018

python - Extract the number from the string line

Have to build a new string which is of the form numeric_token1  numeric_token2 print this in ascending order. (A single space is the separator) (If no numeric tokens are found you need to print  NONE FOUND)


Input : 

        You need to read a line from STDIN to extract the numeric tokens only

Output :

 The string composed of number1  number2 in ascending order   .  Or  NONE FOUND

Test Cases:


Input: velraj hai 123  789 45 done
Output: 45 123 789

Input: 20 new old 90 67
Output: 20 67 90

Program:

def main():
#b = "vel 444 sdfdf 55 sdfdf 44 sdfdf 22 "
#   value = "vel 444 s 5 sdfdf 10 newver 3 sdfdf 1 sdfdf 2 "
   value = raw_input("Enter value :")
   list_array = value.split()

   digit_list = []
   for digit in list_array:
        if digit.isdigit():
#         print digit
            digit_list.append(int(digit))    # Make list to contain the number as interger type

   digit_list.sort()
   print digit_list

#str_ass = " vel "

   str1 = ' '.join(str(e) for e in digit_list)  # This line is used to convert the list into an string formate with space between digits
   if str1:
      print str1
   else:
      print "NONE FOUND"

#   for lis_to_dig in digit_list:
#      str_ass = ' ' + str(lis_to_dig)
#       print lis_to_dig
#    lis_to_arry = digit_list.split()


main()

Output:

$ python extra-num-from-str.py
Enter value :sdfdf 432 vel 22 hsdf 33 sdfdf 1 sdf 5
[1, 5, 22, 33, 432]
1 5 22 33 432