Cipheronics - Codes n' Electronics.

Hot

Post Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Saturday, 26 August 2017

Linux - History

August 26, 2017 0

History of Linux

How it all started?

  • With GNU (GNU is not UNIX) 
  • Richard Stallman made the initial announcement in 1983, Free Software Foundation (FSF) got formed during 1984 
  • Volunteer driven GNU started developing multiple projects, but making it as an operating system was always a challenge 
  • During 1991 a Finnish Engineer Linus Torvalds developed core OS functionality, called it as “Linux Kernel” 
  • Linux Kernel got licensed under GPL, which laid strong platform for the success of Open Source, Rest is history!

How it evolved?

  • Multiple Linux distributions started emerging around the Kernel
  • Some applications became platform independent
  • Community driven software development started picking up
  • Initially seen as a “geek-phenomenon”, eventually turned out to be an engineering marvel
  • Centered around Internet
  • Building a business around open source started becoming viable
  • Redhat set the initial trend in the OS business

Open Source SW vs. Freeware

Open Source Software. Freeware Software
1. Users have the right to access & modify the source codes      1. Freeware is usually distributed in a form of binary at ‘Free of Charge’, but does not open source codes itself.
2. In case original programmer disappeared, users & developer group of the Software,   usually keep its support to the Software.       2. Developer of freeware could abandon development at     any time and then final version will be the last version of the freeware. No enhancements will be made by others.
3. OSS usually has the strong users & developers group that manage and does maintains the project.        3. Possibility of changing its licensing policy.

GPL - General Public Licence

  • Basic rights under the GPL – access to source code, right to make derivative works
  • Reciprocity/Copy-left
  • Purpose is to increase amount of publicly available software and ensure compatibility
  • Licensees have right to modify, use or distribute software, and to access the source code

Problems with the GPL

  • Linking to GPL programs
  • No explicit patent grant
  • Does no discuss trademark rights
  • Does not discuss duration
  • Silent on sub-licensing
  • Relies exclusively on license law, not contract

Read More

C - File Input / Output

August 26, 2017 0

 File Input / Output
  • Sequence of bytes 
  • Could be regular or binary file 
  • Why?
    • Persistent storage 
    • Theoretically unlimited size 
    • Flexibility of storing any type data
Redirection
  • General way for feeding and getting the output is using standard input (keyboard) and output (screen) 
  • By using redirection we can achieve it with files i.e ./a.out < input_file > output_file 
  • The above line feed the input from input_file and output to output_file 
  • The above might look useful, but its the part of the OS and the C doesn't work this way 
  • C has a general mechanism for reading and writing files, which is more flexible than redirection 
  • C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams" 
  • No direct support for random-access data files 
  • To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream 
  • Let's discuss some commonly used file I/O functions

File Pointer

  • stdio.h is used for file I/O library functions
  • The data type for file operation generally is
Type
FILE *fp;
  • FILE pointer, which will let the program keep track of the file being accessed
  • Operations on the files can be
– Open
– File operations
– Close
Functions
Prototype
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *filename);
Where mode are:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Example
#include <stdio.h>
int main()
{
    FILE *fp;
    fp = fopen(“test.txt”, “r”);
    fclose(fp);
return 0;
}

Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *input_fp;
    input_fp = fopen( "text.txt" , "r" );
    if (input_fp == NULL )
    {
    exit(1);
    }
    fclose(input_fp);
return 0;
}
Functions
Prototype
int *fgetc(FILE *fp);
int fputc(int c, FILE *fp);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *input_fp;
    char ch;
    input_fp = fopen( "text.txt" , "r" );
    if (input_fp == NULL )
    {
        exit(1);
    }
    while ((ch = fgetc(input_fp)) != EOF )
    {
        fputc(ch, stdout );
    }
    fclose(input_fp);
return 0;
}
Prototype
int fprintf(char *string, char *format, ...);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *input_fp;
    input_fp = fopen( "text.txt" , "r" );
    if (input_fp == NULL )
    {
        fprintf(stderr , "Can't open input file text.txt!\n" );
        exit(1);
    }
        fclose(input_fp);
    return 0;
}
Read More

Friday, 25 August 2017

C - User Defined Datatypes.

August 25, 2017 0


UDDs – Structures
  • Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. 
  • In circumstances such as these, you can create your own data types which are based on the standard ones 
  • There are some mechanisms for doing this in C:
    • Structures 
    • Unions 
    • Typedef 
    • Enums
  •  Composite (or compound) data type : 
  • Any data type which can be constructed from primitive data types and other composite types 
  • It is sometimes called a structure or aggregate data type 
  • Primitives types – int, char, float, double
 
Example
struct Student
{
 int id;
         char name[30];
         char address[150];
};

int main()
{
struct Student s1 = {10, “Tingu”, “Bangalore”};
          printf(“Struture starts at %p\n”, &s1);
          printf(“Member id is at %p\n”, &s1.id);
          printf(“Member name is at %p\n”, s1.name);
          printf(“Member address is at %p\n”, s1.address);
return 0;
}
Structures - Functions
  • The structures can be passed as parameter and can be returned from a function
  • This happens just like normal datatypes.
  • The parameter passing can have two methods again a normal
    • Pass by value
    • Pass by reference
Structures – Functions – Pass by Value  "Not recommended on larger structures"
Example:
struct Student
{
int id;
        char name[30];
        char address[150];
};
void data(struct Student s)
{
       s.id = 10;
}
int main()
{
        struct Student s1;
        data(s1);
return 0;
}
Structures – Functions – Pass by Reference  "Recommended on larger structures"
Example
struct Student
{
int id;
       char name[30];
       char address[150]
};
void data(struct Student *s)
{
        s->id = 10;
}
int main()
{
         struct Student s1;
         data(&s1);
return 0;
}
Data Alignment
  • A way the data is arranged and accessed in computer memory 
  • When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (4bytes in 32 bit system) or larger. 
  • The main idea is to increase the efficiency of the CPU, while handling the data, by arranging at a memory address equal to some multiple of the word size 
  • So, Data alignment is an important issue for all programmers who directly use memory. 
  • If you don't understand data and its address alignment issues in your software, the following scenarios, in increasing order of severity, are all possible:
    • – Your software will run slower.
    • – Your application will lock up.
    • – Your operating system will crash.
    • – Your software will silently fail, yielding incorrect results.
  • Fetching the character by the CPU will be like shown below
Example
int main()
{
    char ch = 'A';
    int num = 0x12345678;
}
     ● Fetching the integer by the CPU will be like shown below..

Structures – Bit Fields

  • The compiler generally gives the memory allocation in multiples of bytes, like 1, 2, 4 etc., 
  • What if we want to have freedom of having getting allocations in bits?!. 
  • This can be achieved with bit fields. 
  • But not that
    • The minimum memory allocation for a bit field member would be a byte that can be broken in max of 8 bits
    • The maximum number of bits assigned to a member would depend on the length modifier
    • The default size is equal to word size
Example
struct Nibble
{
    unsigned char upper     : 4;
    unsigned char lower    : 4;
};
  • The above structure divides a char into two nibbles
  • We can access these nibbles independently
UDDs – Unions
  • Like structures, unions may have different members with different data types.
  • The major difference is, the structure members get different memory allocation, and in case of unions there will be single memory allocation for the biggest data type
Example
union DummyVar
{
    char option;
    int id;
    double height;
};
  • The above union will get the size allocated for the type double 
  • The size of the union will be 8 bytes. 
  • All members will be using the same space when accessed 
  • The value the union contain would be the latest update 
  • So as summary a single variable can store different type of data as required
UDTs - Typedefs
  • Typedef is used to create a new name to the existing types.
  • K&R states that there are two reasons for using a typedef.
  1. It provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed
  2. Second, a typedef can make a complex definition or declaration easier to understand.
UDTs – Enums
  • Set of named integral values
  • The above example has two members with its values starting from 0. i.e, e_false = 0 and e_true = 1. 
  • The member values can be explicitly initialized 
  • The is no constraint in values, it can be in any order and same values can be repeated 
  • Enums does not have name space of its own, so we cannot have same name used again in the same scope.
Examples
enum Boolean
{
    e_false,
    e_true
};
typedef enum
{
    e_red = 1,
    e_blue = 4,
    e_green
} Color;
typedef enum
{
    red,
    blue
} Color;
int blue;
Read More

Wednesday, 23 August 2017

C - Preprocessor

August 23, 2017 0

Preprocessor
  • One of the step performed before compilation
  • Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation
  • Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol
  • Few advantages of using preprocessor directives would be,
  • Easy Development
  • Readability
  • Portability
  • Preprocessor – Compilation Stages

  • Before we proceed with preprocessor directive let's try to understand the stages involved in compilation. 
  • Some major steps involved in compilation are
    • Preprocessing (Textual replacement) 
    • Compilation (Syntax and Semantic rules checking) 
    • Assembly (Generate object file(s)).
    • Linking (Resolve linkages) 
    The below image provides the flow of these stages.     

  • Preprocessor – Directives

#include             #elif
#define                    #error
#undef                     #warning
#ifdef                       #line
#ifndef                     #pragma
#else                        #
#endif                      ##
#if 
#else
  • Preprocessor – Header Files

  • A header file is a file containing C declarations and macro definitions to be shared between several source files. 
  • Has to be included using C preprocessing directive ‘#include' 
  • Header files serve two purposes:
    • Declare the interfaces to parts of the operating system by supplying the definitions and declarations you need to invoke system calls and libraries.
    • Your own header files contain declarations for interfaces between the source files of your program.
  • Preprocessor – Header Files vs Source Files

  
● Declarations                                 ● Function and variable definitions
● Sharable/reusable                        ● Non sharable/reusable
        ● #defines                                         ● #defines
        ● Datatypes                                       ● Datatypes
● Used by more than 1 file
  • Preprocessor – Header Files - Syntax

Syntax
#include <file.h>
  • System header files 
  • It searches for a file named file in a standard list of system directories
#include “file.h”
  • Local (your) header files
  • It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>
Header Files – Search Path
  • On a normal Unix system GCC by default will look for headers requested with #include <file> in:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
  • You can add to this list with the -I <dir> command-line option
“gcc -print-prog-name=cc1 -v” would search the path info
Header Files – Once-Only
  • If a header file happens to be included twice, the compiler will process its contents twice causing an error
    • E.g. when the compiler sees the same structure definition twice, This can be avoided like:
Example:
#ifndef NAME
#define NAME
/* The entire file is protected */
#endif
Macro – Object-Like
  • An object-like macro is a simple identifier which will be replaced by a code fragment 
  • It is called object-like because it looks like a data object in code that uses it. 
  • They are most commonly used to give symbolic names to numeric constants
Syntax
#define SYMBOLIC_NAME   CONSTANTS
Example
-------
#define BUFFER_SIZE     1024
Macro – Arguments
  • Function-like macros can take arguments, just like true functions
  • To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function like
Example
#include <stdio.h>
#define SET_BIT(num, pos)  (num | (1 << pos))
int main()
{
     SET_BIT(0, 2);
     return 0;
}
Macro – Multiple Lines
  • You may continue the definition onto multiple lines, if necessary, using backslash-newline.
  • When the macro is expanded, however, it will all come out on one line
Example
#include <stdio.h>
#define SWAP(a, b)   \
{                                \
int temp = a;             \
a = b;                         \
b = temp;                   \
}

int main()
{
int num1 = 10, num1= 20;
          SWAP(num1, num2);
          printf(“%d %d\n”, num1, num2);
}
Macro – Standard Predefined
  • Several object-like macros are predefined; you use them without supplying their definitions.
  • Standard are specified by the relevant language standards, so they are available with all compilers that implement those standards
Example
#include <stdio.h>
int main()
{
         printf(“Program: \“%s\” ”, __FILE__);
         printf(“was compiled on %s at %s. ”, __DATE__, __TIME__);
         printf(“This print is from Function: \”%s\” at line %d\n”, __func__, __LINE__);
return 0;
}
Preprocessor – Conditional Compilation
  • A conditional is a directive that instructs the preprocessor to select whether or not to include a chunk of code in the final token stream passed to the compiler
  • Preprocessor conditionals can test arithmetic expressions, or whether a name is defined as a macro, or both simultaneously using the special defined operator
  • A conditional in the C preprocessor resembles in some ways an if statement in C with the only difference being it happens in compile time 
  • Its purpose is to allow different code to be included in the program depending on the situation at the time of compilation. 
  • There are three general reasons to use a conditional.
    • A program may need to use different code depending on the machine or operating system it is to run on 
    • You may want to be able to compile the same source file into two different programs, like one for debug and other as final 
    • A conditional whose condition is always false is one way to exclude code from the program but keep it as a sort of comment for future reference
Conditional Compilation - ifdef
Syntax
#ifdef MACRO
            /* Controlled Text */
#endif
Conditional Compilation - defined
Syntax
#if defined (ERROR) && (WARNING)
    /* Controlled Text */
#endif
Conditional Compilation - if
Syntax
#if expression
    /* Controlled Text */
#endif
Conditional Compilation - else
Syntax
#if expression
         /* Controlled Text if true */
#else
         /* Controlled Text if false */
#endif
Conditional Compilation - elif
Syntax
#if DEBUG_LEVEL == 1
          /* Controlled Text*/
#elif
DEBUG_LEVEL == 2
          /* Controlled Text */
#else
          /* Controlled Text */
#endif
Preprocessor – Diagnostic
  • The directive ‘#error’ causes the preprocessor to report a fatal error. The tokens forming the rest of the line following ‘#error’ are used as the error message
  • The directive ‘#warning’ is like ‘#error’, but causes the preprocessor to issue a warning and continue preprocessing. The tokens following ‘#warning’ are used as the warning message
...
Read More

C - Strings

August 23, 2017 0

Strings

  •  A set of things tied or threaded together on a thin cord

  • Contiguous sequence of characters 
  • Stores printable ASCII characters and its extension.
  • End of the string is marked with a special character, the null character '\0' 
  • '\0' is implicit in strings enclosed with “” 
  • Example: “You know, now this is what a string is!”
Examples:
char char_array[5] = {'H', 'E', 'L', 'L', 'O'};        -  Character Array
char str[6] = {'H', 'E', 'L', 'L', 'O', '\0'};                     -  String
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};                       -  Valid
char str[6] = {“H”, “E”, “L”, “L”, “O”};                       -  Invalid
char str[6] = {“H” “E” “L” “L” “O”};                           -  Valid
char str[6] = {“HELLO”};                                           -  Valid
char str[6] = “HELLO”;                                               -  Valid
char str[] = “HELLO”;                                                 -  Valid
char *str = “HELLO”;                                                  -  Valid
Program Example1:
#include <stdio.h>
int main()
{
    char char_array_1[5] = {'H', 'E', 'L', 'L', O'};
    char char_array_2[] = “Hello”;
    sizeof(char_array_1);
    sizeof(char_array_2);
    return 0;
}
 Output : The size of the array Is calculated So, : 5, 6
Program Example2:
int main()
{
    char *str = “Hello”;
    sizeof(str);
   return 0;
}
Output : The size of pointer is always constant so, : 4 (32 Bit System)
  • String - Manipulations:

Examples:
char str1[6] = “Hello”;
char str2[6];
str2 = “World”;
Conclusion: Not possible to assign a string to a array since its a constant pointer.
char *str3 = “Hello”;
char *str4;
str4 = “World”;
Conclusion: Possible to assign a string to a pointer since its variable

Str1[0] = 'h';
Conclusion: Valid. str1 contains “hello”

Str3[0] = 'w';
Conclusion: Invalid. str3 might be stored in read only section. Undefined behavior
  • String - Sharing

#include <stdio.h>
int main()
{
    char *str1 = “Hello”;
    char *str2 = “Hello”;
    if (str1 == str2)
    {
        printf(“Yep, They share same space!\n”);
    }
    else
    {
        printf(“No, They are in different space\n”);
    }
    return 0;
}
What could be the above output try it yourself.. :)
  • Strings - Library Functions

Read More

Post Top Ad

Responsive Ads Here