EmbLogic's Blog

C programming

  • There is a small, fixed number of keywords, including a full set of flow of control primitives: for, if/else, while, switch, and do/while. There is one user-defined names are not distinguished from keywords by any kind of sigil.
  • There are a large number of arithmetical and logical operators, such as +, +=, ++, &, ~, etc.
  • More than one assignments may be performed in a single statement.
  • Function return values can be ignored when not needed.
  • Typing is static but weakely enforced all data has a type, but implicit conversions can be performed; for instance, characters can be used as integers.
  • Diclearation syntax mimics usage context. C has no “define” keyword; instead, a statement beginning with the name of a type is taken as a declaration. There is no “function” keyword; instead, a function is indicated by the parentheses of an argument list.
  • User-defined (typedef) and compound types are possible.
    • Heterogeneous aggregate data types (struct) allow related data elements to be accessed and assigned as a unit.
    • Array indexing is a secondary notion, defined in terms of pointer arithmetic. Unlike structs, arrays are not first-class objects; they cannot be assigned or compared using single built-in operators. There is no “array” keyword, in use or definition; instead, square brackets indicate arrays syntactically, e.g. month[11].
    • Enumerated types are possible with the enum keyword. They are not tagged, and are freely interconvertible with integers.
    • Strings are not a separate data type, but are conventionally implemented as null-terminated arrays of characters.
  • Low-level access to computer memory is possible by converting machine addresses to typed pointers.
  • Procedurea (subroutines not returning values) are a special case of function, with an untyped return type void.
  • Functions may not be defined within the lexical scope of other functions.
  • Function and data pointers permit ad hoc run time polymorphism.
  • A preprocessor performs macro definition, source code file inclusion, and conditional compilelation.
  • There is a basic form of modularity: files can be compiled separately and linked together, with control over which functions and data objects are visible to other files via static and extern attributes.
    • Complex functionality such as i/o string manipulation, and mathematical functions are consistently delegated to library routines.
Posted in Data Structures with C | Leave a comment

Article on Linux Kernel

The Linux Kernel

 In 1991, a Finnish student named Linus Benedict Torvalds made the kernel of a now popular operating system. He released Linux version 0.01 on September 1991, and on February 1992, he licensed the kernel under the GPL license. The GNU General Public License (GPL) allows people to use, own, modify, and distribute the source code legally and free of charge. This permits the kernel to become very popular because anyone may download it for free. Now that anyone can make their own kernel, it may be helpful to know how to obtain, edit, configure, compile, and install the Linux kernel.

A kernel is the core of an operating system. The operating system is all of the programs that manages the hardware and allows users to run applications on a computer. The kernel controls the hardware and applications. Applications do not communicate with the hardware directly, instead they go to the kernel. In summary, software runs on the kernel and the kernel operates the hardware. Without a kernel, a computer is a useless object.

There are many reasons for a user to want to make their own kernel. Many users may want to make a kernel that only contains the code needed to run on their system. For instance, my kernel contains drivers for FireWire devices, but my computer lacks these ports. When the system boots up, time and RAM space is wasted on drivers for devices that my system does not have installed. If I wanted to streamline my kernel, I could make my own kernel that does not have FireWire drivers. As for another reason, a user may own a device with a special piece of hardware, but the kernel that came with their latest version of Ubuntu lacks the needed driver. This user could download the latest kernel (which is a few versions ahead of Ubuntu’s Linux kernels) and make their own kernel that has the needed driver. However, these are two of the most common reasons for users wanting to make their own Linux kernels.

Before we download a kernel, we should discuss some important definitions and facts. The Linux kernel is a monolithic kernel. This means that the whole operating system is on the RAM reserved as kernel space. To clarify, the kernel is put on the RAM. The space used by the kernel is reserved for the kernel. Only the kernel may use the reserved kernel space. The kernel owns that space on the RAM until the system is shutdown. In contrast to kernel space, there is user space. User space is the space on the RAM that the user’s programs own. Applications like web browsers, video games, word processors, media players, the wallpaper, themes, etc. are all on the user space of the RAM. When an application is closed, any program may use the newly freed space. With kernel space, once the RAM space is taken, nothing else can have that space.

The Linux kernel is also a preemptive multitasking kernel. This means that the kernel will pause some tasks to ensure that every application gets a chance to use the CPU. For instance, if an application is running but is waiting for some data, the kernel will put that application on hold and allow another program to use the newly freed CPU resources until the data arrives. Otherwise, the system would be wasting resources for tasks that are waiting for data or another program to execute. The kernel will force programs to wait for the CPU or stop using the CPU. Applications cannot unpause or use the CPU without the kernel allowing them to do so.

Posted in Project 00: Linux System / Network Administration, Uncategorized | Leave a comment

Article on Linux Administration

 Linux Administration

This article is about the operating system.The Unix operating system was conceived and implemented in 1969 at AT&T’s Bell Laboratories in the United States by Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna. It was first released in 1971, and initially, was written entirely in assembly language, a common practice at the time. Later, in a key pioneering approach in 1973, Unix was re-written in the programming language C by Dennis Ritchie (with exceptions to the kernel and I/O). The availability of an operating system written in a high-level language allowed easier portability to different computer platforms.

With AT&T being required to license the operating system’s source code to anyone who asked (due to an earlier antitrust case forbidding them from entering the computer business),Unix grew quickly and became widely adopted by academic institutions and businesses. In 1984, AT&T divested itself of Bell Labs. Free of the legal obligation requiring free licensing, Bell Labs began selling Unix as a proprietary product.

Linux is any Unix-like and POSIX-compliant computer operating system assembled under the model of free and open source software development and distribution. The main form of distribution are Linux distributions. The defining component of Linux is the Linux kernel, an operating system kernel first released on 5 October 1991, by Linus Torvalds. Because it considers Linux to be a variant of the GNU operating system, initiated in 1983 by Richard Stallman, the Free Software Foundation prefers the name GNU/Linux when referring to the operating system as a whole .

Linux was originally developed as a free operating system for Intel x86-based personal computers. It has since been ported to more computer hardware platforms than any other operating system. It is a leading operating system on servers and other big iron systems such as mainframe computers and supercomputers: as of June 2013, more than 95% of the world’s 500 fastest supercomputers run some variant of Linux,including all the 44 fastest. Linux also runs on embedded systems (devices where the operating system is typically built into the firmware and highly tailored to the system) such as mobile phones,tablet computers, network routers, building automation controls, televisions and video game consoles; the Android system in wide use on mobile devices is built on the Linux kernel.

The development of Linux is one of the most prominent examples of free and open source software collaboration: the underlying source code may be used, modified, and distributed — commercially or non-commercially — by anyone under licenses such as the GNU General Public License. Typically, Linux is packaged in a format known as a Linux distribution for desktop and server use. Some popular mainstream Linux distributions include Debian (and its derivatives such as Ubuntu and Linux Mint), Fedora (and its derivatives such as the commercial Red Hat Enterprise Linux and its open equivalent CentOS), Mandriva/Mageia, openSUSE (and its commercial derivative SUSE Linux Enterprise Server), and Arch Linux. Linux distributions include the Linux kernel, supporting utilities and libraries and usually a large amount of application software to fulfill the distribution’s intended use.

A distribution oriented toward desktop use will typically include the windowing systems X11 and Wayland and an accompanying desktop environment such as GNOME or the KDE Software Compilation. Some such distributions may include a less resource intensive desktop such as LXDE or Xfce for use on older or less powerful computers. A distribution intended to run as a server may omit all graphical environments from the standard install and instead include other software to set up and operate a LAMP or a LYCE solution stack. Because Linux is freely redistributable, anyone may create a distribution for any intended use.

Posted in Project 00: Linux System / Network Administration, Uncategorized | Leave a comment

Character Driver

CHARACTER DRIVER

As we have seen always, there is a Driver which drives every machine automatically or manually. In the same way Driver plays most important role in LINUX. Before we move on to Character Driver lets talk a bit about Device Driver. Device driver is a computer program that simply controls the external devices like Mouse, Keyboard, Pen-drive, USB, Hard-disk, Printer, Scanner, Web-cam etc, Drivers basically depends on hardware and also the operating what you are using.

There are three types of Device Drivers in LINUX.
1.Character Driver.
2.Block Driver.
3.Network Driver.

Character Driver: Character Driver simply means it Read or Write Character by Character only.
There are some set of rules to write a Character Driver. Follow the rules and you can write a best Character Driver.

Initialization: Firstly we have to initialize the kernel module, for which we have to use macro init_module(), this macro is use to initialize our kernel module. This function is called when the module is inserted into the kernel with help of command insmod. Now we have to end our module if we start it and for this we use at the end cleanup_module(). This function has called when module is remove from the kernel and the command is rmmod. These two are the most important part of kernel module. We are using some modules here which means we have to use header file #includethis header file needed by all kernel module. One more header file we use for the initialization of kernel loadable module is #includeand also we need to define two macros at the end of initialization and cleanup function are module_init(init_function); & module_exit(cleanup_function); these are the macros that designates a module is initialization and clean up functions.

After written your first code now is the time to compile it, here in kernel module we need a Makefile for the compilation of our kernel module. After this write make and if you are lucky then you will see a successfully compiled module. After the compilation you can check the ko(Kernel object) file with the help of ls on the command line. Now enter into the modules with the help of command, cd modules.
In the modules insert your kernel object file, write insmod filename.ko. To Check whether the file is insert successfully or not, give command dmesg by which you can see your inserted module. Once the module insert, now is the time to remove it with the help of command rmmod, and again enter dmesg to check whether the module removed successfully or not.

Make sure that there are no errors in your program, because when you work on the character driver is just like you are going to hack the kernel and one single mistake in your program may lead to reboot but reboot means you are lucky, because sometimes due to errors your system may crash. So its better to make your self good in system C.

The above process may have one alternate. Rather than go for that long you can do it by scripting as well. All you need to do just write a script and than change the mode of your scripting file into the executable file by giving command chmod called change mode.

Here the registration of your loadable kernel module is complete. We are making this module for a device, but now we are not using any physical hardware. In the place of this we will assign some memory inside our system which will act as device for our character driver and further testing we will do with the help of that created memory which will create with the help of scull(Simple Character Utility for Loading Localities). We are using scull because it isn’t hardware dependent. Scull using the space which is allocated by the kernel. And also the portability of scull is so easy across the computer architecture on which the linux runs. We allocate memory to to scull with the help of kmalloc.

Now once you allocate memory for scull you should check the major and minor number of your device. Major and Minor number are the most important part for any device access, to check the major and minor write ls -l. Here you can see the major & minor number. Actually why these major and minor number concept we use, because the major number shows that which driver we have to use to acces particular hardware, because system already assign a unique major number for every device, all device files with same major number are controlled by same driver. Now the driver use minor number to distinguish between the various driver it controls. Driver may have same major number but have different minor number.

The command to check the major and minor number is-:
printk(KERN_ALERT “Major no.:%d\n”, MAJOR(dev));
printk(KERN_ALERT “Minor no.:%d\n”, MINOR(dev));

Posted in Character Driver | Leave a comment

Client Server using IPC

IPC stands for inter process communation and with help of this mechanism server can communicate with their appropriate clients.
There are four types of IPC
1)Pipe
2)fifo
3)message queues
4)shared memory

pipe-It is mechanism in which dataflow connect from one process to another.It can occurs only in related process.
The prototype of pipe can be written as
int pipe( fd[2] )
fifo-It is mechanism in which external process also connect with this client server process.It can occurs in related as well as unrelated process also
message queues-It is a mechanism in which we can send unrelated process in easy and efficient way.
It independent of both sending and receiving process
shared queues-It is used to send data between two runnind process.
The project client server using pipe we are using various terms like client,server,processing client,fork(),execl().There are three client ,three processing client and one server is used.
Client who sends the request to the server and server send their request to processing client to process the request after processing the request ,processing resend the information to server and server send to client.In this way server responding the request of client.
Client generate a process by using fork() and send these process to server .server has method execl() through which server will get data from client.
Hence the real advantage of using pipe when we wish to pass a data from one process to another.

Posted in Uncategorized | Leave a comment

IPC

Client Server using IPC

 

IPC stands for inter process communation and with help of this mechanism server can communicate with their appropriate clients.

There are four types of IPC

1)Pipe

2)fifo

3)message queues

4)shared memory

 

pipe-It is mechanism in which dataflow connect from one process to another.It can occurs only in related process.

The prototype of pipe can be written as

int pipe( fd[2] )

fifo-It is mechanism in which external process also connect with this client server process.It can occurs in related as well as unrelated process also

message queues-It is a mechanism in which we can send unrelated process in easy and efficient way.

It independent of both sending and receiving process

shared queues-It is used to send data between two runnind process.

The project client server using pipe we are using various terms like client,server,processing client,fork(),execl().There are three client ,three processing client and one server is used.

Client who sends the request to the server and server send their request to processing client to process the request after processing the request ,processing resend the information to server and server send to client.In this way server responding the request of client.

It is works as program create a pipe and then fork,creating a child process.both have a file discripter that access the file,one for each reading and writing.so,there are four file descripter in total

Client generate a process by using fork() and send these process to server .server has method execl() through which server will get data from client.

Hence the real advantage of using pipe when we wish to pass a data from one process to another.

Posted in Project 03: Client Server Communication using Linux and IPC | Leave a comment

PROJECT 3 : A Linux System Programming using IPC.

A Linux System Programming using IPC.

Many times for any client-server set-up to work efficiently, there arises a problem to share data or resources among various processes that are running.
IPC involves many communication and synchronization techniques used to achieve this, within a network or may be over the network to send/recieve data between two or more running processes.(at transport layer using SOCKETS)

This project is implemented to achieve inter-process communication seemlessly, using various communication and synchronization techniques including PIPEs, FIFOs, MESSAGE QUEUES, SHARED MEMORY, SEMAPHORE and SIGNALS.

General Idea:
There may be 1 server and many requesting clients and a few processing clients.
Many requesting clients may send their requests to the server at any point of time and server maintains a database so as to recognize the request and invoke appropriate processing client to calculate the result of the query.
Also server must send the results of the requests to the associated requesting clients without any loss of data.

1.
In my first attempt i implemented 1 server that itself invokes 3 requesting clients using PIPEs and recieves various requests from them.
After having the requests it invokes appropriate processing clients using another set of 3 processing PIPEs to process the requests and calculate respective results to be sent back to appropriate requesting clients.

Problems Encountered:
1) There was a problem in synchronizing the mechanism.
2) Block on read
3) Block on write.

Remedy:
I implemented signals to synchronize the mechanism.

2.
Then to make requesting clients independent of the server i implemented FIFOs to take requests from various requesting clients and to provide them with appropriate results.
I used 1 requesting FIFO to get all the requests from the requesting clients.
After decoding the request server invokes appropriate processing clients to get the result using PIPEs.
Then the server sends the results to the requesting clients by another FIFO.
The requesting clients also sent their PIDs so as to be signaled by the server.

Problems encountered:
1)Block on open.
2)Block on read.
3)Block on write.
4)Synchronization.

Remedy:
i implemented signals to sync the mechanism.

3.
Then i implemented MESSAGE QUEUE to get the requests from the requesting clients and everything else was same.
The requirement for synchronization was appreciately decreased as there was no need of the processes to be present all the time as was in the case of FIFOs.
The reader or the writer can anytime access the MESSAGE QUEUE to read or write the data along with their PIDs.

Problems encountered in MESSAGE QUEUEs:
1) Max size limited by data chunk of message queue.
2) Max size of queue is also system limited..
Remedy:
I implemented SHARED MEMORY and SEMAPHORES to achieve synchronization.

4.
Now i modified the above architecture and used SHARED MEMORY instead of resulting FIFOto achieve synchronization. Still sync was not apprecisble.
Problem encountered:
Synchronization while sending the results back to the requesting clients was not proper.

Remedy:
Use semaphores.

5.
Finally i implemented each of the above mentioned techniques to implement the project.
The requesting clients used MESSAGE QUEUE to send the requests to the server.
Server, after analysing the requests, invoked appropriate processing client to calculate the result.
Then server used SHARED MEMORY to sent results back to the requesting clients.
SEMAPHORES were implemented to synchronize shared memory access by various requesting clients.

Submitted By:
HARPREET SINGH
Batch no.:
20.02.36

Posted in Project 03: Client Server Communication using Linux and IPC | Leave a comment

ARTICAL NAME:-Programming with c

Emblogic embedded technogies pvt. Lmt.

C programming is a middle level language .It was invented dennis richard in 1972.This language is a popular language and widly used .This language is imperative language.It was designed to compile to relativly starightforward compiler.It is using many cocepts write a c program.

operators are used in c program many types.like assignment operato,logical operator,bitwise operator etc

conditions are used in c program many types. like if conditions, if else condition, etc

looping is used in c program many types .like for loop,while loop, do while loop.but mostly used for loop.

array is used in c program that provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data.All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

In c programming pointer is a variable which contains the address of memory in another variable.Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer.

function in c progrmmin it is module of code that take information that information with local symbolic names called parameters and arguments.

these are concepts are used in c programming to write a program . it is also used any oher concets  in c progrmming.

After these concepts clear i will try to assignments .

Posted in Uncategorized | Leave a comment

THREADS AND SOCKETS

THREADS AND SOCKETS MECHANISMS

 INTRODUCTION OF THREADS: Multiple strands of execution in a single program are called threads. All processes have at least one thread. All threads in a program execute simultaneously and perform their function individually. Threads are the part of a program does not create new process context for multiples threads but shares the code segment , data segment part of a process context only different stacks is created for multiple threads of size of 8MB.

Threads shares file descriptors, signal handlers, current directory, global variables. Threads have it own stack and local variables. With respect to “forking” system does not initialize a new system virtual memory space and environment for a process.In forking with respect to each process a pid is given but in threads pid is given to a main process.

IMPLEMENTION OF  THREAD:

Header file for thread  #include<pthread.h> is included.

Thread is created by pthread_create(). pthread _create()  creates a new thread. The pthread_create() function starts a new thread in a calling process.

 int pthread_create(pthread_t * thread, pthread_attr_t   *attr,void*(*start_routine)(void *), void *arg);

There are four arguments in a pthread_create() function:

(1)pthread_t *thread :-pointer to new thread.

(2)pthread_attr_t *attr:- sets the thread attributes and the attr argument points to pthread_attr_t whose contents are used at the time of thread creation to determines attributes for a new thread. We take attr NULL that means thread is created with default attributes.

(3)void*(*start_routine)(void*):-the address of a function taking a pointer to void as a parameter & the function will return a pointer to void.

(4)void *arg:-The return value is 0 for success or an error if something going wrong.

When thread terminates it call exit function.

Void pthread_exit(void *retal);

this function terminates the thread executing ,the calling function return a pinter to an object.

 Threads are to be join to the main thread by a join calling function.

Int pthread_join(pthread_t th,void ** thread_return);

the first argument is the thread for which to wait and second argument is a pointer toa pointer that itself points to the return value from the thread.

This function returns 0 for success otherwise an error if something going wrong.

Advantages and disadvantages:-

overhead cost is low, better utilization, switching b/w threads are less demanding.

The disadvantage among threads debugging is difficult in multi-threaded program in comparison to single-threaded program because the interactions b/w the threads are very hard to control.

SOCKETS:-  Sockets provide intercommunication b/w server and client across a n/w of computers. Server create socket with (file descriptor) resource assigned using the system call function. A socket is named using the system call bind. Server waits for a client to connect to named socket.

 IMPLEMENTAION OF SOCKETS:-

 There are five call functions in server socket are socket call, bind call , listen call, connect call , accept call.

The header included for sockets are :-

#include<sys/types.h>

#include<sys/socket.h>

(1)Socket call:-

int socket (int domain, int type ,int protocol);

socket() creates an end point for communication &returns a descriptor.

the first argument int domain refers to communication domain which is of two types

domain() selects the protocol family which will be used for communication.

(i)AF_UNIX- local communication

(ii)AF_INET- ipv4 internet protocol

The second argument int type are of two types

(i)SOCK_STREAM- TCP/IP- full duplex byte streams,connection based byte stream, provides sequenced reliable two- way communication.

(ii)SOCK_DGRAM- UDP- not reliable and connectionless

Normally only a single protocol exists to support a particular socket type within a given protocol family thats why the third argument is taken zero. This function returns an file descriptor .

(2)Bind call:- Thisis to basically give name to socket & assign port to socket.

int bind(int sockfd, const struct sockaddr *addr ,socklen_t addrlen);

the sockaddr structure is defined as:-

 struct sockaddr{

sa_family_t_sa_family;

char sa_data[14];

purpose of this structure is to cast the structure pointer in addr in order to avoid compiler warnings. The first argument sockfd is the return fd from the socket call function.

(3)Listen call:- this creates queues in which clients wait for their connections.

int listen(int sockfd , int backlog);

the first argument is the return socket fd. The second argument shows how many number of request want to store in queue.

(1)if queue is full, client may receive an error with an indication of ECONNREFUSED.

(2)request ignored.

(3)on success zero is return and -1 for error is returned.

(4)Connect call:-

          int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

(5)Accept call:- This provide another socket descriptor through which server can chat with its client.

int accept( int sockfd,struct sockaddr *addr, socklen_t * addrlen);

(6)Closed call:-

int close(int fd);

Then for sever clients there are two system calls for are:

(1)Socket call:-To create socket.

(2)Connect call:-:This to provide socket descriptor through which it can chat with server.

 

 

 

 

Posted in Project 04: FTP based Client Server using Threads and Sockets | Leave a comment

Interprocess Communication

“A Process is an address space with one or more threads executing within that address space and required system resources for those threads.”

IPC (Inter Process Communicaton) is a set of methods for the exchange of data between multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. There are several methods to do this like:

a) file : A record stored on the disk that can be accessed by name by any process.

b) Signal: A system message sent from one process to another, not usually used to store information but instead give commands.

c) Socket: A data stream sent over a network interface, either to a different process on the same computer or to another computer.

d) Message Queue: An anonymous data stream similar to the pipe, but stores and retrieves information in packets.

e) Pipe: A two-way data stream interfaced through standard input and output and is read character by character.

f) Named Pipe: A pipe implemented through a file on the file system instead of standard input and output.

g) Semaphore: A simple structure that synchronizes threads or processes acting on shared resources.

h) Shared Memory: Multiple processes given access to the same memory, allowing all to change it and read changes made by other processes.

Process table: It is like a data structure describing all of the processes that are currently loaded with their PID, status, command string, and sort of information. Operating system manages processes using their PID’s. To see the list of processes, we use “ps” command.

eg: ps -ax, ps-af, etc

Pipes:

Pipes provide unidirectional flow of communication between processes within the same system. In other words, they are half-duplex, that is, data flows in only one direction. A pipe is created by invoking the pipe system call, which creates a pair of file descriptors. These descriptors point to a pipe inode and the file descriptors are returned through the filedes argument. In the file descriptor pair, filedes[0] is used for reading whereas filedes[1] is used for writing.
One of the major disadvantage of pipes is that the they can not be accesed using their names by any other process other than child and the parent as they do not get listed in the directory tree.

The work around for this porblem is to create a named pipe which is also called as a FIFO, which stands for First in First out, meaning the data that is written into the pipe first will be read out first always.

FIFO: The fifos get listed in the directory tree and any process can access it using its name by providing the approproiate path.

fifo are created using the function mkfifo() which takes as arguments

1. The name of the fifo that has to be created
2. The permissions for the file.

Once the file is created, it needs to be opened using the system call open() and the data can be read and written from the file using read() and write system calls.

One of the examples you can think of using a named pipe is communication between a server and a client. If ther are two fifos one of the server and the other of the client, then the client can send request to the server on the server fifo which the server will read and respond back with the reply on the client’s fifo.

Another advantage of a fifo over the pipes is that fifo are birectoinal, that is the same fifo can be read from as well and written into.

Shared Memory

Shared memory allows one or more processes to communicate via memory that appears in all of their virtual address space.

shared memory mechanism consisting of four steps. in order of:

  • Creating the segment and connecting -shmget (shared memory get)
  • Using the pointer to get the shared memory address – shmat (shared memory attach),
  • Detaching the shared memory area after use – shmdt (shared memory detach) and
  • Finally using the address to control accesses, permissions, receive information and destroy the shared memory area – shmctl (shared memory control).
Posted in Project 03: Client Server Communication using Linux and IPC | Leave a comment

CHARACTER DRIVER

CHARACTER DRIVER
DEVICE DRIVER: -Device driver is a black box which gives response to a hardware to internal programming interface. Device driver hides the details of working device.

DEVICE DRIVERS ARE OF THREE TYPES:-
1. Character Driver
2. Block Driver
3. Network Driver

Here we will elaborate the working of CHARACTER DRIVER.
in character Driver following are essential function which perform their own specific task:-
Initialization of module
Exit of module
Release function of module from kernel
Creating a SCULL(simple character utility for loadable
locality.
Registering character device in kernel
writing function in character device
Read functionality
Read/write with single threads
Read/write using multiple threaded application using
following synchronization technique:
1. Semaphore and Mutex
2. Completion
3. Spinlock
4. waitque
Proc creat and read
Before staring of functions we should include a common header which contains global headerfile ,global variable and structure which will be describe in functions one by one.
1.INITIALISATION OF MODULE :- Initialisation is main entry point for module in kernel.
module_init is the function which passes address of initialisation function routine as an argument. Printk is output function which prints output. Included headerfiles for init function are #include and #include .
our module named lkm.c can be inserted in kernel after make it by makefile which include path lib/modules/$(shell uname -r)/build .
Our module can be inserted by command insmod lkm.c
lsmod is command uses to check entry of our module in /proc/modules
2.CLEANUP or EXIT FUNCTION OF MODULE:- module can be cleaned up when not in use. This modularity is possible in running state of kernel. rmmod lkm.c is command use to cleanup our moudule. Status of initialisation can be checked using command dmesg which prints message in printk function.

3.REGISTERATION OF SCULL DEVICE:- Before registeration of SCULL device we will create a scull device in header.h which have is type of structure.
Contents of scull device are struct scullqset *scullqset, struct cdev c_dev,quantum_size,data_size,device_size,wcou nt,and qset_size.a global structure scull pointer named *sculldev also declared to take access of scull device.
The registeration of scull device is done using function
alloc_chardev_region which will allocate our device with memory provided by kmalloc function dynamically.
Function kmalloc allocates a continous memory in kernel memory region. In cleanup function module is deallocated using function unregister_chardev_region. And allocatted memory can be free up using function kfree. cdev_del function is used to delete our device from kernel space.
To register our module we needs to add up header file:
#include<linux/module.h
2. #include
3. #include
INITIALISATION OF SCULL DEVICE:
To initialise scull device each element of scull structure should be initialised with finite value. Thease value can be defined as macro in header.h file.in our initialisation we take size as
sculldev->quantum_size=quantum_size;
sculldev->data_size=data_size;
sculldev->qset_size=qset_size;
sculldev->device_size=device_size;
sculldev->scullqset=NULL;
sculldev->wcount=0;
SETUP C_DEV:-
as described in sculldev, cdev is also a another important
parameter of our device which have most important functionality to proceed further:
dev=MKDEV(majorno,lv);
cdev_init(&sculldev[lv].c_dev,&fops);
sculldev[lv].c_dev.owner=THIS_MODULE;
sculldev[lv].c_dev.ops=&fops;
sculldev[lv].c_dev.count=nod;
sculldev[lv].c_dev.dev=dev;
for single device lv=0;
as we can see in first
requrement is to initialise cdev
should be initialised with owner of module
count is no of nod or device
and dev_t dev variable which recognise our module.
And last is address of variable of type structure fileoperation.
OPERATIONS like open,read,write,lseek,release,are mapped
to their corresponding routines with fileoperations structure.
struct file_operations fops=
{
open:scull_open,
release:scull_release,
write:dev_write,
seek:scull_llseek,
read:dev_read
};

OPEN OPERATION:-
To perform any read/write/seek operation on device first we have to open our device using function.
int scull_open(struct inode *, struct file *);
when an user level application will perform a open call routine then open would map to this routine.
Function container_of() will return a address pointing to our device which will be assigned to filep->private_data for further operations.
The mode flags of file permissions can be checked using logical OR( | ) operation of f_flags and O_ACCMODE which is in fileoperations structure defined in #include.

WRITE OPERATION:-
Now its time to write data in device. Before start to write data we should initialise function
struct scullqset
{
void **data;
struct scullqset *next;
};
in structure scullqset double pointer type **data will hold the address of quantums. and single pointer *next will point to the next sullqset. Prototype of write function:-
ssize_t dev_write(struct file *, const char __user *, size_t , loff_t * );
as we see in write functon
1. first parameter is struct file pointer which points to private_data holding the address of our device. And address can be assigned to locally declared variable struct sculldev *lsculldev .
2. Next parameter is __user *buffer which holds data to write in our device come from userspace. Now before writing data in devive further stages are:
allocate memory to struct scullqset
allocate memory to local lscullqset->data qset
allocate memory to lscullqset->data[] quantum
data would be written in quantum using function
copy_from_user defined in #include
3. Third parameter is size of data to write in scullqset.
If size of data is more than 64 byte then create a linklist
and each qset will point to next qset by node *next.
4. The last parameter is offset pointer which allows us position to write in our device. This position is obtained from a flag f_pos in fileoperations structure.
Data writing operation accomplished by writing data in quantum one by one.

READ OPERATION:
Data which have been written in device now can be read from device by user level application using read function.

ssize_t dev_read(struct file *,char __user *,size_t,loff_t *);
as in write function read will also have four parameter to perform task.
1. The pointer of type file will point to the address of device contained in private_data.
2. Second parameter is __user *buffer which holds data read from device by calling function
copy_to_user .
This function will read data from device quantum by quantum and we define size of one quantum is 8 byte.
3.third parameter is size of data to read from device
4. and fourth parameter is offset which directs the pointer to the position to read. If offset is zero then data will be read from starting position.

SYNCHRONIZATION:-
Thare arises some issues when user level applications have more than one thread. And this is possible there may be 100′s of appilications having distinct threads to open,read,write and for close opearation.
In this situation a unpredictable result will be obtained.
There are many malfuctioning of device can happen.
Data can be read before being update(writing).
So we must follow some synchronization technique which helps us to obtain a predecided result.
These synchronisations technique are as:
1. semaphore and mutex
2. spinlock
3. completion
4. waitque

Posted in Uncategorized | Leave a comment

Interprocess communication

Interprocess Communication

Interprocess communication is a technique used for exchange of data between two process and threads.The process can be run on same computer or via internet.IPC  is a mechanism through which two process communicates.Signals are used in IPC to send notification to a process or to specific thread within the same process in order to notify it of an event that occurred. When a signal is sent, the operating system interrupts the target process’s normal flow of execution to deliver the signal. Execution can be interrupted during any non-atomic instruction. If the process has previously registered a signal handler, that routine is executed. Otherwise, the default signal handler is executed.IPC are implemented through Pipe,Fifo,Semaphores,Shared memory,Message queue.

  • The pipe call: function provide a means to transfer data between two programs without invoking the shell to interpret the request command.It also give control over the reading and writing.The pipe function has the following prototype.

#include<unistd.h>

Int pipe(int pipe_descriptor[2]);

 

Pipe is passed apointer to an array of two integer file descriptor.It is important to realize that this is a file descriptor, not a file stream.So we must use low level read and write call to access the data.The real advantage of pipe comes when you wish to pass data beween two process.When a program creates a new process using the fork call,the descriptor that is open previously will remain open.By creating a pipe in the original process and forking to create  anew process.We can pass data from one process to another process down the pipe.By using the fork( ) call ,it creates the new child process.By using the execl( ) command we can replace the whole line with with other program.

You can create a pipe using the following syntax.

if(pipe(file_pipes)==0),creates a pipe.

To write the data into the file descriptor use the sysntax.

Write(file_pipes[1],some_data,strlen(some_data));

To read the data from the file descriptor use the following syntax.

Read(file_pipes[0],buffer,BUFSIZ);

On success the syntax is exit(EXIT_SUCCESS); On failure the sysntax is exit(EXIT_FAILURE);

The program creates a pipe with the pipe call,it then use a fork call to create the new  process.The parent write the data in to the pipe and child process read the data from the pipe.Both the parent and child will exit after the one read and write.The pipe call is us to allow the child to be a different program from its parent rather than just a process running the same program.

 

FIFO: Named pipes (or FIFO) are variants of pipe that allow communication between processes that are not related to each other. The processes communicate using named pipes by opening a special file known as a FIFO file. One process opens the FIFO file from writing while the other process opens the same file for reading. Thus any data written by the former process gets streamed through a pipe to the latter process. The FIFO file on disk acts as the contract between the two processes that wish to communicate.

Creat: A FIFO is created by the mkfifo function:

#include <sys/types.h>

#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);

Open: mkfifo tries to create a new FIFO. If the FIFO already exists, then an EEXIST error is returned. To open an existing FIFO, use open(), fopen() or freopen()

Close: to close an open FIFO, use close(). To delete a created FIFO, use unlink().

 

Posted in Project 03: Client Server Communication using Linux and IPC | Leave a comment

ipc mechanism (pipe and fifo)

IPC MECHANISM

The acronym of IPC is inter process communication. Before we talk about ipc,it is necessary to know about process. Process is defined as,”when one or more than one thread are executing with an address space”
IPC mechanism is a set of methods to exchanging the data between multiple threads in one or more process.There are various methods of IPC just like pipes, fifo, message queue and shared memory.Every mechanism has its own properties.But here I am going to discuss about pipes and fifo only.

Pipe :- A pipe is a mechanism for inter process communication in which data is written to the pipe by one process and read by another process.pipe has no name thatswhy it is known as unnamed process. In pipe data always send in buffer.In pipe data
send in unidirectional.
In pipes when we use fork ( ) it creates a process like a duplicate of main. That means when we use fork there are two processes are generated one is known as parent process and another one is known as child process. Fork returns -1 when forking is failed.when it returns 0 that mean its a child process and when fork return positive value that it is a parent process.
If child process exit before parent process its known as zombie process . If parent process exit before child process then it is known as orphan process . In this case child is managed by Init process.pipe function is declared in header file #include.
three client server program using pipes :- here I have done three client server program using pipes.in which there are three clients and one server and three processing unit.
From clients I sent data using buffer and data sent from client to server using pipe. Then execl function is used in child process of server. And data read from client to server using a file descriptor. Which is send to processing unit by server using write operation by another file descriptor. Then again forking is done in server program and processing unit is called using execl function. In processing unit data transmitted by server is in the form of string thats why we have to use sscanf in processing side to convert data in respective integer and character type.after processing the data result is again converted in the form of string and sent to server using write operation using file descriptor.
Then data read by server using read operation and result sent by server to client using write operation with the help of file descriptor in between client and server.
For the synchronization we can use sleep or wait function.
Same process is done for rest of two clients.we can do this program by using only two pipes , one is used in between client and server and another one is used in between server and processing unit.
FIFO :- The acronym for fifo is first in first out. fifo is also known is named pipe. fifo is a related process.processes open in the fifo by name in order to communicate through it.
The name allows unrelated processes to communicate through it.Multiple processes can open(), write() and read() from the FIFO. open for writing blocks until someone opens for reading .when data write from one side ,it will go on ‘block on write’ if there will be reader in another side and same thing happened if reader tries to read and there is no writer in another side then reader will go on ‘block on read’.
Creating a FIFO:
int mkfifo(const char *path, mode_t mode);
before creating a fifo using mkfifo we use access( fifo_name,flag) to check that the same name of fifo is already created or not. After creating fifo the second step is open the fifo
in write only (O_WRONLY) or read only (O_RDONLY).which returns file descriptor fd. Then read or write operation is perform using this file descriptor.

Posted in Uncategorized | Leave a comment

PROJECT-01(Multiple Data Compression)

 

As per the project started from basics of ‘c’, i.e introduction of c ,syntax and semantics control structures -conditionals ,loops,arrays,strings,project management tools,file io,functions,structures,queus stacks ,searching and sorting.

My part of work and work status is – I had tried to clear the basic concept of c they are -:

->declaring variables

->c pre-processors

->prepossessing statements

->operators in c

->data types->primary data type-> int

char

float

double.

Upto the part above the the topics related are clearly covered and implemented ,and the functions like printf,,scanf,size of a data type were worked and successfully evaluated with control structures and conditionals .the assignments provided by emblogic pvt ltd were very helpful to make the concepts strong and the are also evaluated.

->secondary data type->Arrays

pointers

structures

unions

in the above the topics related and the concept of the above were likely to be cleared, but the

assignments provided by emblogic India pvt ltd were a bit hard and it took time for me to implement.

The above topics on implementation status -arrays are successfully implemented and the others

are partially implemented.

->functions

in the functions of c, the process of creating a function is ->function declaration

->function call

->function definition

the above concepts are covered and i had worked with some examples , but the assignments provided are more conceptual and the required logic for the assignment questions are a bit hard as i felt,and i am working to make the concepts well and to solve the assignment as quick as possible.

->project management tools

->queues

->searching and sorting

searching and sorting techniques could be define as the way to search an element in an array

by different methods like:

searching –->

->linear searching

The above technique is used to find or search an element in a give set of elements or by using linked list.

The technique linear searching was implemented by taking an array i.e a set elements of same data type arranged and stored in a continuous memory location. A particular element had to be given as a input to the existed set of elements and the work to be done is to search the particular element in the given set of elements. The code for the above technique was successfully written and evaluated.

->binary searching

the technique binary searching is a searching technique used to search a element in a given set of elements .this searching technique has the same function as linear searching but the method of searching the element is better and it make min complexes. In this the given set of elements are to be arranged i ascending Oder using the sorting technique .the searching techniques are implemented and successfully evaluated.

 

 

Posted in Data Structures with C | Leave a comment

PROJECT 01(MULTIPLE DATA COMPRESION)

Multiple data compression using C,

INTRODUCTION TO PROJECT
All digital data is stored in form of binary 0s and 1s internally. Working on embedded devices that are memory constrained these files need to be managed efficiently and effectively. Also when transferring file over the network, larger the file size larger is the bandwidth requirement to transfer the same. Hence the requirement of some technique that could take less space and less bandwidth for transmission.

One such technique that can be used for saving memory is compressing the files using some algorithm so that they acquire less space on disk. This technique not only serves the purpose of consuming less space but also provides data security since the file that will be generated after the compression is usually not in human-readable form. Since a normal file does not use all the 255 characters of ASCII table,representing each character by one byte consumes a lot more space. Thus if each distinct character in a file can be represented by fewer bits same data can be saved in much less space;hence accomplishing the purpose.

Here’s the simple stepwise working of the project:-
COMPRESSION
1.) Open the file to be compressed.
2.) Find the distinct characters in the file and store it in an array(master array).
3.) From the master array find the maximum number of bits required to represent each distinct character in compressed file.
4.) Read the file character by character.
5.) Replace each character with the index of the corresponding character in master array.
6.) Manipulate the indexes in the form of 1 byte using shift operations.
7.) Write the manipulated indexes to the compressed file.
8.) Store the master array in other file so that it could be used at the time of decompression.

DECOMPRESSION
1.) Open the compressed file.
2.) Open the file containing master array and store it in array.
3.) Form the master array find out the number of bits used to represent each character.
4.) Read the compressed file character by character.
5.) From this read characters filter out the actual ASCII characters using shift operations and indexes.
6.) Save the filtered out ASCII characters to new file.

Besides this the project can further be enhanced if the master array is also encrypted and this master array is used as the decryption key between the compressing and decompressing programs.

Finally the project was successfully implemented with the very good compression ratio. Also the project was implemented using two techniques;one was using the structured approach based on the number of bits required and the other was a general purpose program in which only a single piece of code could compress or decompress the file.

Posted in Project 2: Multiple Data Compression and Encryption | Leave a comment