Programming


C/C++: Set Affinity to process thread – Example Code 3

The following code sets the affinity of the process thread to a specific CPU core.
In this example, we define the CPU core id using the variable core_id.

Full source code available here [download id=”2363″]


#include <stdio.h>
#include <stdlib.h>
#define __USE_GNU
#include <sched.h>
#include <errno.h>
#include <unistd.h>

// The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong.
#define print_error_then_terminate(en, msg) \
  do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)


int main(int argc, char *argv[]) {

  // We want to camp on the 2nd CPU. The ID of that core is #1.
  const int core_id = 1;
  const pid_t pid = getpid();

  // cpu_set_t: This data set is a bitset where each bit represents a CPU.
  cpu_set_t cpuset;
  // CPU_ZERO: This macro initializes the CPU set set to be the empty set.
  CPU_ZERO(&cpuset);
  // CPU_SET: This macro adds cpu to the CPU set set.
  CPU_SET(core_id, &cpuset);

  // sched_setaffinity: This function installs the cpusetsize bytes long affinity mask pointed to by cpuset for the process or thread with the ID pid. If successful the function returns zero and the scheduler will in future take the affinity information into account. 
  const int set_result = sched_setaffinity(pid, sizeof(cpu_set_t), &cpuset);
  if (set_result != 0) {

    print_error_then_terminate(set_result, "sched_setaffinity");
  }

  // Check what is the actual affinity mask that was assigned to the thread.
  // sched_getaffinity: This functions stores the CPU affinity mask for the process or thread with the ID pid in the cpusetsize bytes long bitmap pointed to by cpuset. If successful, the function always initializes all bits in the cpu_set_t object and returns zero.
  const int get_affinity = sched_getaffinity(pid, sizeof(cpu_set_t), &cpuset);
  if (get_affinity != 0) {

    print_error_then_terminate(get_affinity, "sched_getaffinity");
  }

  // CPU_ISSET: This macro returns a nonzero value (true) if cpu is a member of the CPU set set, and zero (false) otherwise. 
  if (CPU_ISSET(core_id, &cpuset)) {

    fprintf(stdout, "Successfully set thread %d to affinity to CPU %d\n", pid, core_id);
  } else {

    fprintf(stderr, "Failed to set thread %d to affinity to CPU %d\n", pid, core_id);
  }

  return 0;
}

To compile we used the following command

gcc -Wall affinity.c -o affinity;

Full source code available here [download id=”2363″]

For a full pthread example please visit this link.


Java: Methods on how to iterate over a List

Following we present a few methods on how to iterate over a List in Java.

Currently we present:

  1. Using a standard for loop
  2. Using an iterator to loop
  3. Using a For-Each loop
  4. Using Streams

[download id=”2234″]

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ListLooper {

    public static void main(final String[] argv) {

        final String elementsArray[] = new String[] { "First Element", "Second Element", "Third Element" };
        // First of all we convert an array of Strings to a list of Strings, we do this to avoid adding each element to the list we will use by using the add() method.
        final List<String> elementsList = Arrays.asList(elementsArray);

        // Method 1: Using a standard for loop
        System.out.println("Method 1: Using a standard for loop");
        // We will loop N times, where N is the size of the list.
        // Since the first element of the list is on position 0, we start from that and finish at position N-1.
        for (int i = 0; i < elementsList.size(); i++) {

            // Using get() we retrieve the element at position.
            System.out.println(elementsList.get(i));
        }

        // Method 2: Using an iterator to loop
        System.out.println("Method 2: Using an iterator to loop");
        // The Java iterator is an interface that belongs to the collection framework and allows us to traverse a collection and access the data element of the collection without bothering the user about the implementation details of that collection. 
        final Iterator<String> iterator = elementsList.iterator();
        while (iterator.hasNext()) {

            // next() returns the next element in the collection until the hasNext() method returns false.
            System.out.println(iterator.next());
        }

        // Method 3: Using a For-Each loop
        System.out.println("Method 3: Using a For-Each loop");
        // This code works for any object that implements the Iterable interface.
        for (final String element : elementsList) {

            System.out.println(element);
        }

        // Method 4: Using Streams
        System.out.println("Method 4: Using Streams");
        // This code will not work for Java versions earlier than Java 8.
        elementsList.forEach((element) -> {

            System.out.println(element);
        });
     }
}

[download id=”2234″]

Compilation and execution are presented in the next section.


javac ListLooper.java;

java ListLooper;
Method 1: Using a standard for loop
First Element
Second Element
Third Element
Method 2: Using an iterator to loop
First Element
Second Element
Third Element
Method 3: Using a For-Each loop
First Element
Second Element
Third Element
Method 4: Using Streams
First Element
Second Element
Third Element

Following is the Java version used in this article

java -version
openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b16)
OpenJDK 64-Bit Server VM (build 25.111-b16, mixed mode)

Fedora 24: Solution to gcrypt.h: No such file or directory

Recently we tried to compile cisco-decrypt.c* on Fedora 24 (64bit).
We got the full source code from the website of Maurice Massar.
Download full source code here: [download id=”2078″]

We needed this tool to configure the Gnome 3 native network client to connect to a specific Cisco VPN network.
During the configuration we setup a “Cisco Compatible VPN (vpnc)” VPN.

* Please note that this tool is NOT a hacking nor cracking tool. In order for you to make any use of it, you need to have a valid PCF file given to you by your system administrator. It is only useful when you need to get the group password to configure a system that does not accept the PCF file with the encrypted password.

To compile the code you can use one of the following two methods:

Compilation method 1

gcc -Wall -o cisco-decrypt cisco-decrypt.c $(libgcrypt-config --libs --cflags)

If the package libgcrypt-devel is not installed you will get a prompt message as follows, which will instruct you to install the missing package.
You need to type y to both questions so that the installation will proceed. Once the installation is done, execute once more the compilation command.

As you can see below, you might get a whole bunch of errors, ignore them and try to compile once more. It seems to be a bug that will not affect the end result (at least in this scenario).

gcc -Wall -o cisco-decrypt cisco-decrypt.c $(libgcrypt-config --libs --cflags)
bash: libgcrypt-config: command not found...
Install package 'libgcrypt-devel' to provide command 'libgcrypt-config'? [N/y] y

Proceed with changes? [N/y] y

gcc: error: Waiting: No such file or directory
gcc: error: in: No such file or directory
gcc: error: queue...: No such file or directory
gcc: error: Loading: No such file or directory
gcc: error: list: No such file or directory
gcc: error: of: No such file or directory
gcc: error: packages....: No such file or directory
gcc: error: The: No such file or directory
gcc: error: following: No such file or directory
gcc: error: packages: No such file or directory
gcc: error: have: No such file or directory
gcc: error: to: No such file or directory
gcc: error: be: No such file or directory
gcc: error: installed:: No such file or directory
gcc: error: libgcrypt-devel-1.6.6-1.fc24.x86_64: No such file or directory
gcc: error: Development: No such file or directory
gcc: error: files: No such file or directory
gcc: error: for: No such file or directory
gcc: error: the: No such file or directory
gcc: error: libgcrypt: No such file or directory
gcc: error: package: No such file or directory
gcc: error: libgpg-error-devel-1.24-1.fc24.x86_64: No such file or directory
gcc: error: Development: No such file or directory
gcc: error: files: No such file or directory
gcc: error: for: No such file or directory
gcc: error: the: No such file or directory
gcc: error: libgpg-error: No such file or directory
gcc: error: package: No such file or directory
gcc: error: Waiting: No such file or directory
gcc: error: in: No such file or directory
gcc: error: queue...: No such file or directory
gcc: error: Waiting: No such file or directory
gcc: error: for: No such file or directory
gcc: error: authentication...: No such file or directory
gcc: error: Waiting: No such file or directory
gcc: error: in: No such file or directory
gcc: error: queue...: No such file or directory
gcc: error: Downloading: No such file or directory
gcc: error: packages...: No such file or directory
gcc: error: Requesting: No such file or directory
gcc: error: data...: No such file or directory
gcc: error: Testing: No such file or directory
gcc: error: changes...: No such file or directory
gcc: error: Installing: No such file or directory
gcc: error: packages...: No such file or directory

Compilation method 2

In case the above method does not work for you for some reason, you can try the following.

gcc -Wall -o cisco-decrypt cisco-decrypt.c -lgcrypt

If the package libgcrypt-devel is not installed you will get an error as follows.

gcc -Wall -o cisco-decrypt cisco-decrypt.c -lgcrypt
cisco-decrypt.c:30:20: fatal error: gcrypt.h: No such file or directory
 #include <gcrypt.h>
                    ^
compilation terminated.

In this case use

sudo dnf install libgcrypt-devel

to install the missing library and try again to compile.

To use

Open your PCF file with a text editor. Find the line that starts with enc_GroupPwd= and copy the characters after that.

Paste the characters as the first command line argument to the newly compiled application. The password will be the line returned right after.


./cisco-decrypt 886E2FC74BFCD8B6FAF47784C386A50D0C1A5D0528D1E682B7EBAB6B2E91E792E389914767193F9114FA26C1E192034754F85FC97ED36509
Th!sIsMyK3y#

Other notes

In the case you get these errors:

/tmp/ccHrH1kZ.o: In function `c_decrypt':
cisco-decrypt.c:(.text+0x243): undefined reference to `gcry_md_hash_buffer'
cisco-decrypt.c:(.text+0x267): undefined reference to `gcry_md_hash_buffer'
cisco-decrypt.c:(.text+0x2b4): undefined reference to `gcry_md_hash_buffer'
cisco-decrypt.c:(.text+0x31d): undefined reference to `gcry_cipher_open'
cisco-decrypt.c:(.text+0x33b): undefined reference to `gcry_cipher_setkey'
cisco-decrypt.c:(.text+0x356): undefined reference to `gcry_cipher_setiv'
cisco-decrypt.c:(.text+0x382): undefined reference to `gcry_cipher_decrypt'
cisco-decrypt.c:(.text+0x391): undefined reference to `gcry_cipher_close'
/tmp/ccHrH1kZ.o: In function `main':
cisco-decrypt.c:(.text+0x41e): undefined reference to `gcry_check_version'
collect2: error: ld returned 1 exit status

It most probably means that you did not add on your compilation command one of the following two parameters

  1. $(libgcrypt-config –libs –cflags)
  2. -lgcrypt

You need one of these two options to be on the command line to compile.


An Introduction to Elm Series: Solution to ‘Binary Tree’ example supplementary module ‘Queue’

In http://elm-lang.org/examples/binary-tree, we are given a basic implementation of a binary tree and we are asked to extend it in various ways.

One of the tasks asked us to traverse the tree in various ways, in order to implement the Breadth First Traversal we needed a Queue.

Following is the code that we used for the Queue that is based on this package http://package.elm-lang.org/packages/martinsk/elm-datastructures/2.0.0/Queue.

The solution that this module was used in can be found here http://bytefreaks.net/programming-2/elm/an-introduction-to-elm-series-solution-to-binary-tree-example under the -- Breadth-first section.


module Queue exposing (Queue, init, enqueue, dequeue, length, foldr, foldl, map, fromList, toList)

{-| This Module implements a simple LIFO queue

# Definition
@docs Queue

This is based on the

# Fundamentals
@docs init, enqueue, dequeue, length

# Usefull functions
@docs foldr, foldl, map, fromList, toList

-}

{-| a simple queue.
-}
type alias Queue a = (List a, List a)

{-| Creates an empty queue -}

init : Queue a
init = ([], [])


{-|Enqueue an element on a queue -}
enqueue :  a -> Queue a -> Queue a
enqueue a (inqueue, outqueue) =
  ((a::inqueue), outqueue)

{-|Dequeues an element of the end of a queue, and also returns thel
element -}

dequeue : Queue a -> (Maybe a, Queue a)
dequeue (inqueue,outqueue) =
  case outqueue of
    [] ->
      case inqueue of
        [] -> (Nothing,(inqueue, outqueue))

        (_::_) -> dequeue([], List.reverse inqueue)

    (x::xs) ->
      (Just x, (inqueue, xs))


{-| Get the length(number of elements) in the queue -}
length : Queue a -> Int
length (inqueue, outqueue) =
  let
    inqueue_len  = List.length inqueue
    outqueue_len = List.length outqueue
  in
    inqueue_len + outqueue_len

{-| Fold across a queue front ot back -}

foldr : ( a -> b -> b) -> b -> Queue a -> b
foldr f acc (inqueue, outqueue) =
  List.foldl f (List.foldr f acc inqueue) outqueue

{-| Fold across a queue back ot front -}

foldl : ( a -> b -> b) -> b -> Queue a -> b
foldl f acc (inqueue, outqueue) =
  List.foldr f (List.foldl f acc outqueue) inqueue


{-| maps from a queue of type a to a queue containing elements of type
b -}

map : (a -> b) -> Queue a -> Queue b
map f (inqueue, outqueue) =
  (List.map f inqueue, List.map f outqueue)


{-| converts a queue into a list  -}

fromList : List a -> Queue a
fromList l =
  (l, [])


{-| converts a list into a queue  -}

toList : Queue a -> List a
toList (inqueue, outqueue) =
  inqueue ++ (List.reverse outqueue)

You can download the module from here [download id=”1835″]