Modern Education

All about Process in Linux/Unix – Developer Perspective

PROCESS:

In Linux every thing we sees executing or taking some action will be by the process. Processes carry out tasks within the operating system. For definition ” Any program in execution is called process”.  A program is a set of machine code instructions and data stored in an executable area of memory.

Processes are separate tasks each with their own rights and responsibilities. Each individual process runs in its own address space and not interacting with another process except through secure, kernel managed mechanisms.

LINUX PROCESS:-

An instance of a program is called a Process. In simple terms, any command that you give to terminal on your Linux machine starts a new process. Having multiple processes for the same program is possible. A process itself not a process, until it comes info execution.

In a Linux system no process is independent of any other process. Every process in the system, except the initial process has a parent process. New processes are not created, they are copied, or cloned from previous processes.

Types of Process:-

  • Foreground Process: A foreground process is any command or task you run directly and wait for it complete. They run on the screen and need input from the user.

A foreground Process begins by typing a command at prompt. For example, list of files in current directory

>ls
  • Background Processes: In Linux, a background process is nothing but process running independently. They run in the background and usually do not need user input.

For example

  • Antivirus in your computer, normally it is running in background.

 

Basic command for Linux process:-

ps:

The ps command is used to provide information about the currently running process, including their process identification number(PID).

The basic syntax of ps is

>ps

When ps is used without any option, which display default  information of process currently running on the system .

The four items are labeled PID,TTY,TIME,CMD

PID-  Process identification number.

TTY- TTY is the name of console or terminal shows currently console.

TIME- Time is the amount of CPU, time in minutes and seconds that the process has been running.

CMD- Cmd is the name of the command that launched the process.

 

 

 

 

ps –e:-

ps –e command is used for list of all process running on the system in a single shot

>ps –e
  • –e show all process not just those belonging to user.

 

 

 

 

 

 

 

 

 

 

 

 

pstree:-

pstree is a command that shows the running processes as a tree fromat. It  is  used as a alternative to the ps command.

The basic syntax of the pstree is

>pstree

pstree command is similar to the ps command, but instead of listing the running processes ,it shows in a tree format.

 

 

 

 

 

 

 

 

 

 

bg:-

Linux treats everything as file, even the processes as files under /proc directories. The processes are basically program in execution, they also called jobs

The bg command is the processes that have been stopped by some interrupt signal can be continued background with bg command

Syntax for bg command

  • ./output &

 

 

 

fg:-

The  fg command  is like bg command Except that instead of sending a command in the background it runs them in foreground and occupies the current terminal and wait for process to exit.

top:-

In Linux, top is a command used to display processor activity of your linux , this command shows the  information of the system and the list of processes  which are currently running in the Linux

 

 

 

 

 

 

 

 

 

 

 

 

  • PID:Shows task’s unique process id.
  • PR: Stands for priority of the task.
  • SHR:Represents the amount of shared memory used by a task.
  • VIRT:Total virtual memory used by the task.
  • USER:User name of owner of task.
  • %CPU: Represents the CPU usage.
  • TIME+:CPU Time, the same as ‘TIME’, but reflecting more granularity through hundredths of a second.
  • SHR:Represents the Shared Memory size (kb) used by a task.
  • NI:Represents a Nice Value of task. A Negative nice value implies higher priority, and positive Nice value means lower priority.
  • %MEM: Shows the Memory usage of task.

 

Kill

kill command in Linux (located in /bin/kill), is a built-in command which is used to terminate processes manually. kill command sends a signal to a process which terminates the process.

 

EXAMPLES

> kill -9 -1        Kill all processes you can kill.

> kill -l 11         Translate number 11 into a signal name.

> kill -L             List the available signal choices in a nice table.

> kill 3453         Send the default signal, SIGTERM, to all those processes.

 

Now we will learn the Process with the developer prospective, here user can write C program using any editor wish and compile code using GCC.

Process  Identification:-

In Linux, User can be running various programs in the system, each running program must be unique identified by the kernel and program id identified by its own process is called “PID”, therefore process can be further categorized into

  • Parent process.
  • Child process.

Parent process-Parent process is processes that create other processes during run-time.

In command prompt, Command to get the parent process identity.

Header file need to include for getpid():

  • Sys/types.h
  • unistd.h
getppid()

Child process-Child process are created by the parent process by cone of it ,it will be behaves same as parent.

In command prompt, Command to get the child process identity.

Header file need to include for getppid():

  • Sys/types.h
  • unistd.h
getpid()

 

Now our first steps is to create process, fork is the system call which is used to create process. read on and follow –

Frok():-

Fork is a way to create new processes, fork() operation create a separate processes as a copy of itself then, the copy called the “child process”.

The child process has an exact copy of  the parent process. After the fork, both processes not only run the same program

The child has its own unique process ID and this PID not match the ID of any existing process

The child parent process ID is the same as the parent’s process ID.

Return value:

On success, the PID of the child is returned in the parent, and “0” is returned in the child. On failure, “-1” is returned in the parent, no child process is created and errno is set appropriately.

 

Header file need to include for fork:

 

unistd.h

 

 

 

 

 

 

 

 

 

 

 

Sleep():-

In Linux, Sleep() I s causes the calling thread to sleep either until of real-time specified in seconds have to elapsed .

Steps for sleep():-

Step 1– write a source code for sleep(), as shown in below image.

Step 2– Search for PID in all current running processes, by giving command ps.

Step 3-Enter in /proc and search that Pid by using ls command.

Step 4– Enter the Pid proc type cat status for the process states. Now you should be in /proc/pidof_yourprocess. Steps shown below.

$cd /proc <┘

$ls <┘

$cd  /proc/pid <┘

$cat status <┘

Now see the status of process, it will show process is sleeping.

 

 

 

 

 

 

 

 

 

 

 

 

 

Now check the status of process, that is sleeping.

 

 

 

 

 

 

 

 

 

wait system call

wait()  blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction.

Header files for wait:

  • sys/wait.h

 

 

 

 

 

 

 

 

 

 

Exec System calls family:-

 

  • Exec family of function or system call replace current process with new process.
  • There are various function used in the Exec  like
    • Execl
    • Exclp
    • Execle
    • Execve
    • Execvp
    • Execvpe

Header file need to include is

unistd.h

Example for execlp:-

 

 

 

 

 

 

 

 

Orphan process:-

Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally.

An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention.

An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism.

Zombie process

Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit or crashes . Once this is done using the wait system call, the zombie process is eliminated from the process . This is known as the zombie process.

Professional Training Institute is the top embedded training institute in Bangalore, where student can learn the practical embedded system, we believe in hands on knowledge of subject such that student are not only getting the practical knowledge but also getting experience in embedded system development. All our students are able to get placed in top companies with the knowledge they gain in our institute. come and explore the possibilities, of amazing knowledge you can gain.

INTERFACING LCD 16*2 WITH 8051

INTERFACING LCD 16*2 WITH 8051

SUMMERY:

Connecting LCD 16*2 display to the 8051 microcontroller in 8 bitration method and also passing two commands.

COMPONENTS RECQURIED:

o 8051 Microcontroller
o 16*2 LCD Display
o Switch
o Binary Wires
o Power Supply

PIN DIAGRAM:

 

 

 

 

 

 

 

 

 

SOURCE CODE:


#include 
# define lcd P0 
sbit rs=P1^0; 
sbit e=P1^1; 
sbit b=P1^2; 

void dealy50ms(int a); 
void intial(char b); 
void delay1s(unsigned char c); 
void write1(); 
void write2(); 
void write3(); 
void write4(); 
void button() 
{
	int k=1; 
	while(k==1)
	{ 
		if(b==0)
		{ 
			intial(0x01); 
			k=0; 
		}
	}
} 

void display(char *d); 

int main() 
{ 
	b=1; 
	while(1)
	{ 
		intial(0x38); 
		intial(0x0c); 
		intial(0x01); 
		intial(0x80); 
		write1(); 
		intial(0xc0); 
		write2(); 
		button(); 
		intial(0x80); 
		write3(); 
		intial(0xc0); 
		write4(); 
	} 
} 

void display(char *d)
{ 
	for(*d;d!=NULL;d++)
	{ 
		lcd=*d;
		rs=1; 
		e=1; 
		delay1s(1); 
		e=0;
	}
} 
void write1()
{ 
	display("Done LCD16*2 ");
}

void write2() 
{
	display(" SUCESS ");
}

void write3() 
{
	display("Thank");
}

void write4()
{
	display("YOU");
}

void intial(char b) 
{
	lcd=b;
	rs=0;
	e=1;
	dealy50ms(2);
	e=0; 
} 

void dealy50ms(int a) 
{
	inti=0; 
	for(i; i < a ; i++) 
	{
		TMOD=0x01;
		TH0=0xff; 
		TL0=0xfc;
		TR0=1; 
		while(!TF0);
		TF0=0;
		TR0=0; 
	}
}

void delay1s(unsigned char c)
{
	int i,j;
	for(i=0;i < c;i++)
	{
		for(j=0;j<20;j++) 
		{
			TMOD=0x01; 
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1;
			while(!TF0);
			TF0=0;
			TR0=0;
		}
	}
}

EXPLIANATION:

Now we will go through code and understand how LCD is working. Any C programalways start with main function. In our code main function contains.


int main()
{ 
	b=1; 
	while(1)
	{ 
		intial(0x38); 
		intial(0x0c); 
		intial(0x01); 
		intial(0x80); 
		write1(); 
		intial(0xc0); 
		write2(); 
		button(); 
		intial(0x80); 
		write3(); 
		intial(0xc0); 
		write4(); 
		} 
	}
}
Main function is started
intial(0x38); command 0x38
intial(0x0c);Passing 0x0C value for Display ON, Cursor OFF
intial(0x01);Passing 0x01 value for Clear the screen
intial(0x80);Passing 0x80 value for Force curser to the 1st line in first position
Write1();Calling write1 function to pass the “Done LCD 16*2 ” string to display function

Next how to send the commands through intial function to LCD


void intial(char b) 
{ 
	lcd=b; 
	rs=0; 
	e=1; 
	dealy50ms(2); 
	e=0; 
}
In Intial function, Passing the command from Microcontroller P0 to LCD through parallel communication from Microcontroller(P0.0-P0.7) to LCD(D0-D7). “rs” register pin used to set 1 or 0 is used to sending commands. “e” enable pin used to given value to LCD as making high to low.
Professional Training Institute is highly focus on practical embedded system training in Bangalore, Above post is writtern by our student Joy and Prathavi. We wish bright carrer ahead to both of them.

Next is interfacing button to the LCD to send different string data

 


void button()
{ 
	int k=1; 
	while(k==1)
	{ 
		if(b==0)
		{
			intial(0x01); 
			k=0; 
		} 
	}
}
In button function, Run the while part to check every time the value of k. b is connected to the switch when it pressed it becomes zero, It is initially high condition(1). Passing the value 0x01 to clear the screen. Once button is clicked the value of “k” changed to 0 to exit the while loop.

Next to pass the string value to the LCD through display function

 


void display(char *d)
{ 
	for(*d;*d!=NULL;d++) 
	{ 
		lcd=*d; 
		rs=1; 
		e=1; 
		delay1s(1); 
		e=0; 
	} 
}
Display function getting the string’s first address. rs is the register pin used to intimate the LCD as it is a data not a command. e is a enable pin used to given value to LCD as making high to low.

Next delay function for 50ms

 


void dealy50ms(int a)
{
	inti=0; 
	for(i;i<a;i++)
		{
			TMOD=0x01;
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1; 
			while(!TF0); 
			TF0=0; 
			TR0=0; 
			} 
		}
}
Here is the delay function for 50ms you maximize the value through passing number to make higher, this is done trough using Timer concept

Next is the delay for 1s

 


void delay1s(unsigned char c)
{ 
	inti,j; 
	for(i=0;i<c;i++) 
	{ 
		for(j=0;j<20;j++) 
		{ 
			TMOD=0x01; 
			TH0=0xff; 
			TL0=0xfc; 
			TR0=1; 
			while(!TF0); 
			TF0=0; 
			TR0=0; 
		} 
	} 
}
Here is the same but used delay function for 1s you maximize the value through passing number to make higher, this is done through using Timer concept

From above the program it is written for 8 bitration of 16*2 LCD display for 2 commands. Here I used common initialisation command for all 16*2 LCD display which is in intial( ); and the strings are written in write1..4( ) functions and the display commands of working procedures also written in the display( ) function and also two different delays are represented as 50ms and 1s in delay50ms( ) and delay1s( ) function which is written in timer concept.
Professoinal Training Institute is focus in Practical embedded system training in Bangalore. This post is written by our student Joy and Prathavi, based on their executed experiments during training. we wish then for their bright career ahead.

Alternet Working Source Code:


#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 

void main() 
{ 
	inti=0; 
	int j=0; 
	int k=0; 
	int l=0; 
	int check = 1; 
	unsigned char a[9]="EMBEDDED"; 
	unsigned char b[8]="DESIGN"; 
	unsigned char c[6]="THANK"; 
	unsigned char d[4]="YOU"; 
	button =1; 
	lcd_int(); 

// LCD Initilization 
// button = 1; 

	while( a[i] != '\0' )
	{
		lcd_data(a[i]);
		i++;
		delay_ms(50);
	} 
	lcd_command(0xC0); // Command to Move Cursor to next line 
	while(b[j] != '\0') 
	{
	lcd_data(b[j]);
	j++; 
	delay_ms(50);
	}
	lcd_command(0x0C); // Command to set Display ON Curser OFF 
	//delay_ms(2000); // Delay for 2sec 
	while(check==1)
	{ 
		if(button == 0)
		{
			lcd_command(0x01); // Command To clear screen 
			check = 0; 
		} 
	} 
	while(c[k]!='

#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 
void main() 
{ 
inti=0; 
int j=0; 
int k=0; 
int l=0; 
int check = 1; 
unsigned char a[9]="EMBEDDED"; 
unsigned char b[8]="DESIGN"; 
unsigned char c[6]="THANK"; 
unsigned char d[4]="YOU"; 
button =1; 
lcd_int(); 
// LCD Initilization 
// button = 1; 
while( a[i] != '\0' )
{
lcd_data(a[i]);
i++;
delay_ms(50);
} 
lcd_command(0xC0); // Command to Move Cursor to next line 
while(b[j] != '\0') 
{
lcd_data(b[j]);
j++; 
delay_ms(50);
}
lcd_command(0x0C); // Command to set Display ON Curser OFF 
//delay_ms(2000); // Delay for 2sec 
while(check==1)
{ 
if(button == 0)
{
lcd_command(0x01); // Command To clear screen 
check = 0; 
} 
} 
while(c[k]!='\0') 
{ 
lcd_data(c[k]);
k++;
delay_ms(50); 
}
delay_ms(20); 
lcd_command(0xC0); // Move cursor to nest line 
while(d[l]!='\0') 
{ 
lcd_data(d[l]); 
l++; 
delay_ms(50); 
} 
while(1);
} 
/*................. END of Main Function .........................*/ 
/*................. Delay Sub Routile............................*/ 
void delay_ms(int d) 
{
inti,j; 
for(i=0; i<d; i++)
for(j=0; j<1257; j++); 
}
/*.....Sub Routine to send information over LCD...............*/ 
void lcd_data(char display_data)
{
Display_Port = display_data; 
RS = 1; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*....... Sub Routine to send Commands over LCD Display.............*/ 
void lcd_command(char command) 
{ 
Display_Port = command; 
RS = 0; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*........... Sub Routine to initilize the Commands............*/ 
void lcd_int()
{
lcd_command(0x38); 
delay_ms(10); 
lcd_command(0x0F); 
delay_ms(10); 
lcd_command(0x01); 
delay_ms(10); 
lcd_command(0x80);
delay_ms(10); 
}
') { lcd_data(c[k]); k++; delay_ms(50); } delay_ms(20); lcd_command(0xC0); // Move cursor to nest line while(d[l]!='

#include 
#define Display_Port P0
// Selecting a display port P0 
sbit RS = P1^0; 
// Selecting Resistor Selection 
Port P1.0 
sbit EN = P1^1; 
// Port P1.1 for Enable Pin 
sbit button = P1^2; 
void delay_ms(int d);
// Function Prototype to generate mili second delay 
void lcd_data(char display_data); 
// Function Prototype to send information on LCD display 
void lcd_int(); 
// Function Prototype to initilization of Basics LCD Commands 
void lcd_command(char command); 
// Function Prototype to send commands on LCD Port 
/* .................Begining of Main Function .....................*/ 
void main() 
{ 
inti=0; 
int j=0; 
int k=0; 
int l=0; 
int check = 1; 
unsigned char a[9]="EMBEDDED"; 
unsigned char b[8]="DESIGN"; 
unsigned char c[6]="THANK"; 
unsigned char d[4]="YOU"; 
button =1; 
lcd_int(); 
// LCD Initilization 
// button = 1; 
while( a[i] != '\0' )
{
lcd_data(a[i]);
i++;
delay_ms(50);
} 
lcd_command(0xC0); // Command to Move Cursor to next line 
while(b[j] != '\0') 
{
lcd_data(b[j]);
j++; 
delay_ms(50);
}
lcd_command(0x0C); // Command to set Display ON Curser OFF 
//delay_ms(2000); // Delay for 2sec 
while(check==1)
{ 
if(button == 0)
{
lcd_command(0x01); // Command To clear screen 
check = 0; 
} 
} 
while(c[k]!='\0') 
{ 
lcd_data(c[k]);
k++;
delay_ms(50); 
}
delay_ms(20); 
lcd_command(0xC0); // Move cursor to nest line 
while(d[l]!='\0') 
{ 
lcd_data(d[l]); 
l++; 
delay_ms(50); 
} 
while(1);
} 
/*................. END of Main Function .........................*/ 
/*................. Delay Sub Routile............................*/ 
void delay_ms(int d) 
{
inti,j; 
for(i=0; i<d; i++)
for(j=0; j<1257; j++); 
}
/*.....Sub Routine to send information over LCD...............*/ 
void lcd_data(char display_data)
{
Display_Port = display_data; 
RS = 1; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*....... Sub Routine to send Commands over LCD Display.............*/ 
void lcd_command(char command) 
{ 
Display_Port = command; 
RS = 0; 
EN = 1; 
delay_ms(1); 
EN = 0; 
} 
/*........... Sub Routine to initilize the Commands............*/ 
void lcd_int()
{
lcd_command(0x38); 
delay_ms(10); 
lcd_command(0x0F); 
delay_ms(10); 
lcd_command(0x01); 
delay_ms(10); 
lcd_command(0x80);
delay_ms(10); 
}
') { lcd_data(d[l]); l++; delay_ms(50); } while(1); } /*................. END of Main Function .........................*/ /*................. Delay Sub Routile............................*/ void delay_ms(int d) { inti,j; for(i=0; i<d; i++) for(j=0; j<1257; j++); } /*.....Sub Routine to send information over LCD...............*/ void lcd_data(char display_data) { Display_Port = display_data; RS = 1; EN = 1; delay_ms(1); EN = 0; } /*....... Sub Routine to send Commands over LCD Display.............*/ void lcd_command(char command) { Display_Port = command; RS = 0; EN = 1; delay_ms(1); EN = 0; } /*........... Sub Routine to initilize the Commands............*/ void lcd_int() { lcd_command(0x38); delay_ms(10); lcd_command(0x0F); delay_ms(10); lcd_command(0x01); delay_ms(10); lcd_command(0x80); delay_ms(10); }

Interview Q and A 9

Interview Q and A 9



Ques 1. How to know the given controller is little endian or big endian ?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    unsigned int x=0xaa55;
    unsigned char *p=&x;
if(*p == 0x55)
{
    printf("\n Little endian");
    printf("%x = %x\n",p, *p);
    printf("%x = %x\n",(p+1),*(p+1));
}
else
    printf("\n Big endian");
    return 0;
}


Ques 2. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=5;
    {
      int a=9;
      printf("\n %d",a);
    }
    printf(" %d",a);
    return 0;
}

Ans. 9 5


Ques 3. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=5;
    {
      a=9;
      printf("\n %d",a);
    }
    printf(" %d",a);
    return 0;
}

ans :  9 9



Ques 4. What is the difference between General purpose os and RTOS ?

RTOS :
  Rtos scheduling is based on priority
  Resopnse time is predictable
  kernel is preemptive or upto maximum degree
  priority inversion is a major issue
  it has less memory

Ex: Free RTOS, vxworks, RT linux, PSOS, VRTX, Lynx

General Purpose OS:
  GPOS scheduling  can be adjusted dynamically for optimized throuhput.
  Resopnse time is not predictable
  kernel is non preemptive or upto maximum degree
  priority inverson is unnoticed.
  it is having large memory.
 Ex: Microsoft windows, Redhat Linux, Apple MacOS


Ques 5. explain the meaning of below declaration?

const int PI, int const PI, const int *p,  int * const p, const int *const p;

const int PI : PI is a integer constant.
int const PI : PI is a integer constant.
const int *p:  p is a pointer to constant integer, data present in p is constant and ponter is not constant.
int * const p: pointer p is constant and data is not constant.
const int * const p: both pointer p and data are constant. 


Ques 6. what are the bitwise operators and its types?

bitwise operators are as mentioned below:

| bitwise or operator   
& bitwise and operator
~ bitwise 1's complement operator
^ bitwise xor operator
<< bitwise left shift operator
>> bitwise right shift operator.


Ques 7. which operator is suitable for checking perticular bit is set or not?
 >> and & operators.


Ques 8. what is the output for the below code?
int main()
{
    int a=3;
    int x=-15;

    a+x > 5? puts("a+x > 5 "): puts("a+x < 5");

    return 0;
}


ans: a+x < 5


Ques 9. write a program to swap two numbers without using third variable?

swap(int *p, int *q)
{
  *p=*p+*q;
  *q= *p-*q;
  *p=*p-*q;
}


Ques 10. write a program to pass array as argument to a function?

fun(int p[])
{
  int i=0;
  for(; i<3; i++)
  printf(" = %d \n", p[i]);

}

int main()
{
    int a[3] ={2,3,4};
    fun(a);
    return 0;
}


Ques 11. what is ohms law?
ohms law states that the current through the conductor is directly proportional to the voltage across
the two points of the conductor with resistance is constant.


Ques 12. what is the difference between call by value and call by reference ?
	call by value means we are passing copy of the original arguments to the formal arguments of the function.
             here the value changed in the formal arguments will not affect the original arguments 
	call by referece means we are passing the address of the arguments to the formal arguments of the function.
             here the value changed in the formal arguments will affect the original arguments.

Ques 13. what is the output for the below code if integer size is 4 bytes?

int main()
{
	int x=-1;
	printf("%x ", (x>>1));
	return 0;
}

ans : ffffffff


Ques 14. what is the equivalent pointer expression for the array element arr[i][j][k][m]?

ans:     *(*(*(*(arr+i)+j)+k)+m)


Ques 15. what is the output for the below code?

int main()
{
	int *p, **q, ***r;
	int x=9;
        p=&x;
	q=&p;
	r= &q;
	printf("%d %d %d", *p, **q, ***r);
	return 0;
}

ans: 9 9 9



Ques 16. what is the requirement of infinite loop in embedded system?

	Since embedded system has to continuously work and respond to the inputs, and some other jobs in loop. 
to make the system to run continuously for long time it has to be kept in infinite loop. 
Otherwise it will run only once and stops.



Ques 17: explain about ALU?
 ALU is present in the microprocessors  and microcontrollers. it will do the arithmetic and logic operations
 that is required to be done on instructions. The cpu is powerful if the design of the ALU good. It consumes
 more power and it releases more heat. This is why faster cpus consume more power releases more heat.

Interview Q & A 8

Interview Q & A 8



1. write a code for removing repeated digits in a number?
ex : number = 45678678 here the digits 6,7,8 has to be removed.



2. write a code to search the largest element in the array of your choice?



3. write a program to convert the integer string to number using atoi function.?


4. write a source code to find the sum of 1/3+1/5+1/7+ ....+1/n using recursive function?


5. write a code for linked list print function in reverse order?


6. what is the difference between address of variable and address of ponter variable, 
   explain using an example?


7. write a source code for insert a char/word/substring into a string?


8. can we return multiple values from the function explain with an example?


9.  what is the output for the below code?
	static int k= 8;
	int main()
	{
		if(-k)
		printf("%d", k);
		printf("error");
	}


10. what are the errors in the below source code?

int add();
int main()
{
	printf("function ",add());
}

int add()
{
	int x=5,y=4,z;
	z=x+y;
	printf("%d",z);
}


11. explain for the below code, the memory allocated is safe or not?

struct person
{
char per_name[10];
int per_age;
};
int main()
{
struct person *per;
per=(struct per*)malloc(sizeof(struct person));
free(per);
return 0;
}


12. explain the memory is safe for the below mentioned code?

struct person *per;
per=(struct person*)malloc(sizeof(struct person)*100);
char pername[] = "ptinstitute.in" ;
per = *pername;
free(per);
return 0;


13 what is the output for the below code explain?

char *name="ptinstitute.in";
char  name1[]="ptinstitute.in";
printf("%d %d ",strlen(name),strlen(name[]));
printf(" %d %d",sizeof(name++),sizeof(name[0]));


14. what is the output for the below program explain?
int main()
{
	int x=4,y=2,p,q,r;
	p=x||y;
	q=p&&x;
	r=p^q;
printf("%c %x %d",p,q,r);
return 0;
}


15. what is the output for the below code explain?

int main()
{
int p=4;
for( ;p++;printf("%d",p))
{
printf("ptinstitute.in");
}
return 0;
}

16. what is the output for the below program?

int main()
{
static int m=3;
main();
printf("%d",m++);
return 0;
}


answers:

10.  no errors. 
     output: 9 function

11. safe, because memory is allocated to pointer per.

12. here memory allocated to per , 
    then per = *pername         //it stores the 'p' in the per variable.
    we copying the ascii value of p to pointer p which gives runtime error.
    the allocated memory is not freed, so memory leakage happened here.

13. the prototype of strlen is
       size_t strlen ( const char * str );
    we need to pass the address of the string to find the length.
    in the program we passing strlen with name[], we are passing without index.
    we suppose to pass the address of the string. that is why it gives compile time error.
14. ascii character for 1, 1 0

15. it gives an lengthy loop, in the for loop we incrementing p++ in condition checking position,
    p++ doing continuously and the loop stops after p=0.

16 It gives an runtime error like stack over flow issue.
   here we are not exiting the recursive function main, it is calling continuously main recusively.



Interview Q & A 7

Interview Q & A 7



Ques 1. what is the priority inversion?
	If a low priority task holds the shared resource using semaphore that is required by the high priority task.
The high priority task has to wait till it completes the task. This is done by increasing the low priority 
task to high till it completes the task and once the finishes the task then it releases the resource to
high priority task. This is called priority inversion.


Ques 2. what are different memory segments of a program?

The memory segments are 

Stack segment:
	Here the local variables , arguments passed to the function, function return address, 
interrupt return address will be stored in stack. Stack grows from high memory to low memory.

Heap segment : This segment is used to allocate memory dynamically. It grows from low memory ot high.
we can allocate memory to pointers here.	
	
Uninitialised data segment:
Uninitialised data will be stored here.

Initialised data segment:
Initialised data will be stored here

Code segment:
The code and the constants will be stored here.


Ques 3. what is the difference between polling and interrupt?
	Polling : the system checks the IO devices is they need any cpu service and then do its service, this is called polling
        Interrupt: the IO device request the cpu to execute its service. this is called interrupt.

Some difference between interrupt and polling as follows:
Inerrupt:
	Device notify cpu that it needs cpu attention.
	Interrupt is a hardware mechanism
	An interrupt request line indicates the device needs a cpu service
        Interrupt handler services the device.
	The cpu is disturbed only when the device needs service, here the cpu cycles are saved.
        An inetrrupt can occur at any time
        Inerrupt is in efficient if the devices interrupting the cpu frequently

Polling:
	CPU checks in regular interval if any device is ready for service. 
	Polling is software mechanism.
	Command ready bit indicates the device is ready for service.
	CPU service the device
	Cpu has to check whether a device needs service regularly this wastes lots of cpu cycles.
        CPU Polls the devices at regular intervals. 
	polling becomes inefficient if the cpu finds the device rarly ready for the service.
	

Ques 4. what is semaphore?
 Semaphore is proposed by Dijkstra in 1965 is very significant technique, for solving the synchronisation issue in parallel processing.
Semaphore is simply nonnegative variable holding a number and shared between threads. 
This variable is used to solve critical section problem and to achieve process sychronisation mechanism.

There are two types of semaphores
  Binary semaphore: it is also called as mutex lock. when the thread want to use a resource then it take the
  semaphore uses the resource then it release the semaphore.

  Counting semaphore: it is used when the resources are more than one. If the thread wants to use the 
  resource then it take the semaphore and decrease the semaphore count, if another thread wants the resource then 
  it take the semaphore and decrement the count. After using the resource they release the semaphore and increment the count. 



Ques 5. what is mutex?

	Mutual exclusion object shortly called as Mutex.  Mutex is a locking mechanism. The thread uses the mutex, 
lock the mutex uses the resources then the same thread unlock the mutex. Only one process can use the mutex at a time.
Mutex allows the all threads to use mutex but one at a time.
The program requests the system to create a mutex object for a resource with an ID. when the thread wants to use the resource 
it will lock the mutex uses the resource then it unlocks the resource.


Ques 6. What is synchronous communication?
example communication happened between two people over the telephone.
communication happened with respect to clock signal is called synchronous communication.
synchronous devices require the clock has to be same in receiver and transmitter.
The receiver can sample the signal at the same time interval as the transmitters send the data.


Ques 7. what is watchdog timer?

the watchdog timer continuously counts and some malfunction occured in the system it will reset the system.
The watchdog timer has to be serviced before the watchdog timer expires. if some malfunction occured in system, then it wouldnot service
the watchdog timer. then it will reset the system.


Ques 8. Find the size of the structure ?

struct st1{
int var1;
char ch1;
int var2;
float f1;
};

Ans : 16 bytes.
 In 32 bit system the memory is allocaed in 32 bit size. To make the memory accessing faster it write/reads 32 bit data at a time.
thats why it allocates 4 bytes to char.and others to 4 bytes as usual. in case of char one byte for data and other 3 bytes store garbage.
to effectively use the memory all chars to be placed at one place, other 4 byte sized datatypes at another location.
we can pack the datatypes using #pragam pack(1) defination above the main function.


Ques 9. Convert Binary to decimal for the below numbers?
11001111

ans: 
1 * 2^0 = 1 *1 = 1
1 * 2^1 = 1 *2 = 2
1 * 2^2 = 1 *4 = 4
1 * 2^3 = 1 *8 = 8
0 * 2^4 = 1 *0 = 0
0 * 2^5 = 1 *0 = 0
1 * 2^6 = 1 *64 = 64
1 * 2^7= 1 *128 = 128
------------------------
                  207


Ques 10. find the size for the following?

char arr[6];
int iarr[8];
int *p;

the sizeof arr is 6 bytes
the sizeof iarr is 32 bytes
the sizeof p is 4 bytes


Ques 11. write the truth table for xor gate & or gate?

the truth table for XOR gate:
A   B   O/p
1   1    0
0   0    0
1   0    1
0   1    1

the truth table for OR gate:
A   B   O/p
1   1    1
0   0    0
1   0    1
0   1    1



Ques 12. what is the output for the below code?

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

int main()
{
    int  arr[8] ={0,1,2,3,4,5,6,7,8};
    int i;
    for(i=2; i<8 ;i++)
        arr[arr[i]] = arr[i];
    for(i=0; i<8 ; i++)
        printf("%d ", i, arr[i]);
    return 0;
}

ans: 0 1 2 3 4 5 6 7

Interview QA5

Interview QA5



Ques 1. what is the use of voltile qualifier?

If the variable is declared as volatile , the variable may updated by external program or hardware.
The volatile variable is not optimized by the compiler.
The volatile always read from memory instead of from registers.


Ques 2. what is the use of const keyword?
If the variable is declared as const. then the value of the varible would not be changed by the program.
it is not updated by the user.

const int MAX = 78;
const char STR[10] = "welcome";



Ques 3. what is the use of static variables?

If the variable is declared as static globally, then it is accessible only inside the file where it is declared.
we could not access outside the file.

If the local varible is declared as static inside the function then it is accessible inside the function only.
The varible is initialised only in first call to function. In the next call of the function static variable hold
the previous value will not initialise .

The static variable stored in memory.
The life of the variable is till the program is running.



Ques 4. write a c program to validate the user name and password?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char username[4][20]={ "user1", "user2", "user3", "user4"};
    char password[4][20] = {"password123", "password456", "password678", "password567"};
    char usern[20], passwordn[20];
    int i=0, j=0, k=0, uname=0, passw=1;

    while(1)
    {
    printf("\n enter the username to login:");
        scanf("%s", usern);
    printf("\n enter the password to login:");
        scanf("%s", passwordn);

    for(i=0; i<4; i++)
    if(strcmp(username[i], usern) == 0)
    {
        uname=1;
            for(j=0; j<4; j++)
            if(strcmp(password[j], passwordn) == 0)
            {
                printf("\n both username and password correct.");
                passw=1;
                break;
            }

    }
    if(uname==0)
        printf("\n entered the wrong username");
    if(passw ==0)
        printf("\n entered the wrong password.");
    else
        break;
    k++;
    if(k==3)
    {
     printf("\n you are exceeded 3 chances to enter password and username.");
     break;
    }
    }
    return 0;
}
 


5. what is optimization in c program?

Optimization is the method of improving the code efficiency and quality.
c program can become less in size, occupies less memory space, speed execution is more. 

The methods of code optimization are:
1. Optimization in loops: 
1.1 unroll small loops: 
 	Instead of calculating and storeing the known constant values, we can directly calculate and initialise.

     factorial number calculation:

program1:
int main()
{
    int fct[6];
	int i;
        fct[0] =1;
	for(i=1; i<6; i++)
		{
		    fct[i] = fct[i-1] *i;		
		}
1, 2 6 24 120
    return 0;
}


program 2: modified program of program1
int main()
{
    int fct[6] = {1, 2, 6, 24, 120};

    return 0;
}

1.2. Avoid calculation in loops:
   we should avoid calculating the in loops which will give same value in all iterations.

example1:
int main()
{
    int x=3, y=4, z=6, m=4;
    int g[100], p;

    for(p=0; p<100; p++)
        g[p] = (x*y+z*m) * p;

    return 0;
}


optimized code of example1:
int main()
{
    int x=3, y=4, z=6, m=4;
    int g[100], p;

    int temp= (x*y+z*m);
    for(p=0; p<100; p++)
        g[p] =  temp* p;

    return 0;
}

1.3. Avoid pointer dereference in loop: 
   since it creates lots of work in memory to access the data each time, so dereference 
   before the loop using some temporary variable.

example1:
int main()
{
    int x=0, p;
    int *q=&x;

    for(p=0; p<100; p++)
        *q = *q+p;
    printf("\n %d ", *q);

    return 0;
}

optimized code of example1:

int main()
{
    int x=0, p;
    int *q=&x;
    int t=*q;

    for(p=0; p<100; p++)
        *q = *q+p;
    *q=t;
     printf("\n %d ", *q);

    return 0;
}

1.4. user register storage class for loop variables: it will increase the speed of accessing the variables.

example1:
int i, temp=0;
for(i=0; i<100; i++)
{
   temp= temp+i;
}

optimized code for example1:
int temp=0;
register int i=0;
for(i=0; i<100; i++)
{
   temp= temp+i;
}

2. Increasing Speed of mathemetical calculation:

2.1 avoid not required division operations, since division operation decreases the speed of execution.

	int x=2,y=3,z=4,m=5,n=6;
	x=y+z+(x/y/z/m)+n;

    we can make modify it as
        x = y+z+(x/(y*z*m)) + n ;  

2.2 Multiplication and Division by power of 2 : 
we can use << for multiplication by 2 and we can use >> for division by 2. 
These shift operations are faster than multiplication and division operation so we can 
use them. the compiler will optimize the code incase of complex expression code
it is advised to do bitshifting.

multiplying by 6 : m= (m<<1)+ (m<<2)
multiplying by 7: m= m<<3 - m
devide by 4      : m = m>>2

2.3 : simplying the complex code expression: 
by simplyfying the expression we can reduce the number of mathematical computations.

Ex:
     z=  a*b +a*b*c+ a*b*c*d 
     z= a*b*(c*(1+d))
here we reduced the 6 multiplication 3 addtion to 3 multiplication and 1 addition.

3 Optimizing the switch statements:

 In c switch statements if case labels are continuous then the compiler creates a jump table and it is faster.
 If it is not then it will creates a if else statements. Compiler will put the most frequent conditions first and
 rarely used at later. so keep the most used cases first and rarely used labels later.

 
ex1: 
 switch(exp)
{
case x:
        different expression
	break;
case y:
        different expression
	break;
case z:
	common statements1;
        different expression
	common statements2;
	break;
case m:
	common statements1;
        different expression
	common statements2;
	break;
case n:
        different expression
	break;
}

modified of example1 for code optimization:

 switch(exp)
{
case x:
        different expression
	break;
case y:
        different expression
	break;
case z:
case m:
common statements1;
switch(exp)
	{
        different expression
	break;
case m:
        different expression
	break;
}
	common statements2;
case n:
        different expression
	break;
}

4. prefer int instead of char or short:
 since the char are converted to int then do the calculation after doing the calculation
 it again converted to char.
 if it doing in a loop it affects lot on performance.

5. pre-increment is preferred than post -increment
  
In pre increment the value is just increment by 1 and copies the value to variable location. 
In post increment the value is copied to temporary variable then it inremented and then it copies the value to variable. 

6. order of expression evaluation:

   ex1 : A || B   Here if A is true then no need to check the B so first we have to keep the exprission most of the times evaluates to true.
   ex2 : A && B   Here if A is false then no need to check the B so first we have to keep the exprission most of the times evaluates to false.


6. can we pass structure be passed by value to a function?

yes, we can pass structure to function by value.

#inclue<stdio.h>
#include <stdlib.h >
struct s{
int d;
}s2;

fun(struct s s2)
{
printf("%d \n ", s2.d);
}

int main()
{
    s2.d=45;
fun(s2);
    return 0;
}


7. why cannot we pass arrays to function by value?
	since array have many elements so individual elements we can pass,
     but without the address we cannot access all the elements. so we cannot pass arrays by value to function.

8. difference between macro and inline funtion?

difference in evaluation:
  - the macro is replaced by it code during preprocessing
  - the inline function is parsed by the compiler.

 - In macro the expression passed as arguments are copied to the variables.
 - in inline the expression passed as arguments are evaluated then copied to variables.

#include

#define CUBE(M) M*M*M
inline int cube(int m)
{
	return m*m*m;
}

int main()
{
	printf(" %d",CUBE(1+2));
	printf(" %d",cube(1+2));
	return 0;
}

output:
7 27

for macro it become  1+2*1+2*1+2 = 1+2+2+2= 7
for inline function  3*3*3 = 27

- macro would not check the type of the arguments
- inline funtion check the type checking for arguments passed.

- macro always expanded by the preprocessor 
- inline function is depend on the compiler decesion to replace it by its code.



9. is the recursive function can be inline?

The compiler decides whether the declared function is inline or it can be treated as normal  function.
The recursive functions are treated as normal function by the compiler even though we declared it as inline.

#include <stdio.h>

int cnt=0;
inline int cube(int m)
{
    cnt++;
    if(cnt<=3)
        cube(m);
    else
    return m*m*m;
}

int main()
{
    int x;
    x=cube(2);
    printf("\n %d",x);
    return 0;
}


10. #define abc(x,y) x##y concatenates but abc( abc(x,y)) gives warning why?

abc(x,y) gives xy which substituted in the inside function .
For the outer function will get 1 argument instead of two , so it gives compiler error.



11. can we declare volatile variable?
 yes we can declare. the variable is constant for the program it is declared.
 but the external program or hardware can change it.

Interview Q & A 6

Interview Q & A 6



Ques 1. write a c program to print "Goodmorning" without using ; ?

ex1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
if(printf("\n Goodmorning"))
}

ex2:
#include <stdio.h>
#include <stdlib.h>
int main()
{
while(!printf("\n Goodmorning")){}
}

ex3:
#include <stdio.h>
#include <stdlib.h>
int main()
{
switch(!printf("\n Goodmorning")){}
}


Ques 2. exchange / swap two numbers without using third variable?

program 1:

#include <stdio.h>
#include <stdlib.h>
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m+n;
 n = m-n;
 m = m-n;
 printf("\n m =%d n=%d ", m,n);
    return 0;
}

program 2:
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m+n-(n=m);

 printf("\n m =%d n=%d ", m,n);
    return 0;
}
program 3:
int main()
{
 int m,n;
 m=2;
 n=5;
 m=m^n;
 n=m^n;
 m=m^n;
 printf("\n m =%d n=%d ", m,n);
 return 0;
}
program 4:
int main()
{
 int m,n;
 m=2;
 n=5;
 m = m - ~n - 1;
 n = m + ~n + 1;
 m = m + ~n + 1;

 printf("\n m =%d n=%d ", m,n);
    return 0;
}




Ques 3. what is dangling pointer in c?

Initially a pointer has been pointing some variable location, later the pointer pointing to the memory location
is deleted. but the pointer still pointing to same memory location.
This pointer is called dangling pointer. the error is called dangling pointer error.

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

int main()
{
 int m=34;
 int *p=(int*)malloc(4);
 *p=m;
 free(p);
 printf("\n m =%d ", *p);
    return 0;
}



Ques 4. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int * fun()
{
   int x=44;
    return &x;
}

int main()
{
 int m=34;
 int *p;
 p =fun();

 printf("\n m =%d ", *p);
 return 0;
}

Ans: runtime error/ garbage value prints, since the scope of the local variable 
x is only inside the function fun(), so we can get the address of this variable.
so this is called dangling pointer error.

solution: if we make x as static then it works.



Ques 5. what is wild pointer in c?

A pointer which is not initialised is called wild pointer, 
it returns the some random address and garbage value.

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

int main()
{
  int *p;

 printf("\n p =%u =%d", p,*p);
 return 0;
}

output:  it gives garbage value or prints nothing. NULL pointer means pointing to memory location 0, 
wild pointer means it pointing to some unknown location and gives some garbage value.



Ques 6. what is the advantage and disadvantage of arrays in c?

The advantage : once the array is declared the memory is allocated and we can access each element by using the array indexes.
                it can store elements of the same data type.
               we can declare array for different data types like int , float, struct, union.
               we can initialise the array while declaration.
		an array pointing to the address of the other elements is called pointer array.
disadvantage: if the array index goes out of boundary then there is a huge mistake, some wanted data will be 
              overwritten or the program may crash.
              if array size is more than the usable then the remaining memory is wasted.


array declaration example:
int arr[4];
char str[33];
short int sarr[34];
float fr[12];
int (*funptr[4])();
long *larr[21];
double **p[5];



Ques 7. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>

int main()
{
 double d1=33.44, d2=33.55, d3=66.78;
 double *dptr[3] ={&d1, &d2, &d3 };

 printf("\n %e", *dptr[0]);
 return 0;
}

ans : 3.344 e+001

Here dptr is a pointer array  it points to the elements d1,d2,d3.



Ques 8. explain about do while loop and write a program?
	do while loop we can use to execute the code in the loop before checking the condition.
	it executes the loop atleast one time.

#include <stdio.h>
#include <stdlib.h>
int main()
{
 int i;
 do {
    printf("\n this is do while loop");
 } while(i !=0);
 return 0;
}



Ques 9. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int i;
i=45;
main()
{
printf("\n %d", i);
return 0;
}

ans:
it gives compilation error, since assignment outside main function is not allowed.



Ques 10. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
static int i=10;
int main()
{
for(i=0; i<5; i++)
{
    static int a=3;
    printf("%d ", a++);
}
 return 0;
}

ouput : 3 4 5 6 7

static variable initialises only once, so the variable a prints 3,4,5,6,7



Ques 11. what is the output for the below code?

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

static int i=10;
int main()
{
{
    static int a=3;
    printf("%d ", a++);
}
    printf("%d ", a);
 return 0;
}

output:
it gives compiler error because the static variable declared within the block is local to the block.
we cannot access outside of it.



Ques 12. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
static int a=10;
void fun();
int main()
{

   printf("%d ", a++);
   printf("\nmain b= %d",b);
 return 0;
}
int b=323;
void fun()
{
printf("\n b= %d",b);
}

output: compiler error since the global variable b has to be declared above the main function.



Ques 13. what is the output for the below code in two different files file1.c and file2.c?

//file1.c

#include <stdio.h>
#include <stdlib.h>
extern int sum();
static int i=3, j=5;
int main()
{
    int p;
    p=sum();
    printf("%d ", p);
    return 0;
}

//file2.c

#include <stdio.h>
#include <stdlib.h>
extern int sum();
static int i=3, j=5;
int main()
{
    int p;
    p=sum();
    printf("%d ", p);
    return 0;
}

output:
It gives compiler error, since the global static variables declared i,j are only accessed in file1.c file, 
we cannot access it in file2.c file.
global static variables declared accessed only in the file where they are declared.



Ques 14. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int main()
{
int k=0;
{
   static int p=5;

PRINT:
    printf(" %d", p);
    p++;
    k++;
}
    if(k<4)
        goto PRINT;
    return 0;
}

output|: 5 6 7 8

The life of static varible still exists the control come out and go inside the block.



Ques 15. what tells the prototype of a function ?

prototype of a function is declaration of a function.
it tells the return type of the function,
it tells the input arguments the function takes.
it tells the function name

ex:
int fun(float, char);


Ques 16. what is the output for the below code?

#include <stdio.h>
#include <stdlib.h>
int main()
{
const int k=20;
int *p;
p=&k;
*p=34;

printf("%d", *p);
    return 0;
}

output: 34
we can modify the constant variables in c using pointers.



Ques 17. what is the output for the below code?

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

int search(char);
int (*fun())(char c);

int main()
{
    int m=0;
    int (*p)(char);
    p=fun();
    m=(*p)('h');
    printf("%d", m);
    return 0;
}

int search(char d)
{
    return d;
}

int (*fun())(char g)
{
    return search;
}


output:
104

p=fun()
m=(*p)('h')
m=(*fun())('h') // since p=fun();
m= (*&search())('h')  // since fun returns &search
m= search('h')
m=104.



Test your C skills

Interview Q & A 4



Ques 1. what happens for the below code since the array subscrit is more
 than the size of the array?

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int arr[3] ={3,4,5};
	arr[5]=4343;
}

options:
A. The arr[5] hold the value no issue.
B. Some valid data will be overwritten and the program may crash.
C. compiler error
D. the array size increases


Ques 2. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int m=1, n=1;
    for(; m; printf("%d %d\n", m++, n), m=n++<=2);   

    return 0;
}

options:
A. 1 1 1 2 1 3
B. 1 1 2 2 3 3
C. 2 1 3 2 4 2
D. 1 1 0 2 0 3
 

Ques 3. which of the below options is correct about the uart communication?

options:
A. Uart reads the buffer register and transmit data in parallel.
B. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit data in parallel.
C. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit data in parallel.
D. Transmit data in buffer register, UART adds start bit, parity, stop bits to the data, then tranmit serially.


Ques 4. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    enum color{red, green, blue}s;
    printf("%d\n",sizeof(s));
    return 0;
}

options:
A. 2
B. 4
C. 1
D. 8


Ques 5. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x=1, y=3, z=8, m=0, n=2;
    x = (x || (y=z)) && (m || (y=n));
    printf("%d %d %d %d %d",x,y,z,m,n);

    return 0;
}

options:
A. 1 2 0 8 2 
B. 1 0 2 2 8
C. 1 2 8 0 2
D. 0 2 2 1 8


Ques 6. what is the output for the below code?
#include <stdio.h>
#include <stdlib.h>
int add( int x, int y)
{
    return x+y;
}

int sub( int x, int y)
{
    return x-y;
}

int mul( int x, int y)
{
    return x*y;
}

int divide( int m, int n)
{
    return m/n;
}

int (*f[4])(int x, int y)={add, sub, mul,divide};

int main()
{
 int x=3, y=2, i;

 for(i=0; i<=3; i++)
    printf("%d ", (*f[i])(x, y));

    return 0;
}


options:
A. compiler error
B. 5 1 6 1
C. runtime error
D. 5 1 6 1.5


Ques 7. what are the features of the function?

  - code is more readable.
  - testing the code is easier
  - recursive call can be done for functions
  - each functionality can be kept seperately


Ques 8. what is the output for the below code?

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

int * fun();

int main() {
      int *q;
      q=fun();
      printf("%d",*q);
      return 0;
    }

int * fun() {
      int g=25;
      g--;
      g--;
      return &g;
      }

options:
A. 23
B. 25
C. compiler error
D. runtime error


Ques 9. How the build process happens in c program?

options:
A. Preprocessing, compilation, linking
B. compilation, Preprocessing, linking
C. linking, Preprocessing , compilation
D. none of the above


Ques 10. when we found the undefined function error while building the c program?

options:
A. linking
B. preprocessing
C. compilation
D. none of the above


Ques 11. using volatile keyword for the below code is valid ?

#include <stdio.h>
#include <stdlib.h>
volatile int m=3;
    int main() {
      int h=3,i;
      for(i=0; i<5; i++)
        h=m;
      return 0;
    }

options:
A. since it is in loop not valid
B. it is valid the value of m may change
C. it gives compiler error
D. none of the above


Ques 12. if one wants to transmit data to 4 receivers within the distance of 50 feet with a speed of 6mbs
so which protocol is suitable for this?

options:
A. rs232
B. rs245
C. rs422
D. rs485


Ques 13. which of the following is correct?

options:
A. SPI speed is lesser than I2C and UART
B. SPI uses the chip select signals to select the slaves
C. Multi master is possible in SPI communication
D. SPI will communicate with one slave



Answers

1. B 2. A 3. D 4. B 5. C 6. B 8. D 9. A 10. A 11. B 12. C 13. B

Embedded System QA II

Embedded system Q and A


1. what is difference between microprocessor and microcontroller?

microprocessor microcontroller
The microprocessor is having less in built memory and no inbuilt peripherals like ADC, SPI, IIC, UART, etc. The microcontroller is having more memory and inbuilt peripherals like ADC, IIC, SPI, UART.
The microcontroller is used to build embedded system with less external interfaces. The microprocessor is used to build general purpose computer.
The microcontroller cost is less. The microprocessor cost is more.
Microcontroller having less instructions and more bit handling instructions. Microprocessor having more instructions and few bit handling instructions.

2. what is clock cycle?
Clock cycle is the time duration between two clock pulses of an oscillator. The speed of a controller is more if number	of clock cycles per second is more. Microcontroller speed is measured using number instructions executes per second.

3. How to calculate the clock frequency of a contoller?
It is the frequency of the oscillator we are using to generate clock is the clock frequency of the controller. 

4. what is oscillator?
Oscillator is a circuit which produces the continuous alternating waveform without any input. Crystal osillator is an electronic oscillator circuit that uses the mechanical resonance of a vibrating crystal to create an electric signal with a precise frequency.

5. What is the difference between serial and parallel communication?

In Serial communication data is transmitted serially bit by bit. In parallel communication data is transmitted parallely all the bits in one time.Serial communication needs less number of wires for connection. Parallel communication needs more wires for connection.


6. what is difference between rs232 and rs485?

RS232 RS485
The cable length limited to lesser than 50 feets. It is supporting long distance similar to rs422.
RS232 is single ended susceptible to noise since transmit and receive lines sharing the same ground. it supports multiple command and multiple listening devices and rs422 supports single command and multiple listeners.
Not multidrop - you can connect one rs232 device per port. if we want to connect to 3 meters to a pc we need rs232 protocol ports. rs485 uses 2 wires, twiested interface
Ground is common between tx and rx device, Need minimum 3 wire to communicate since the communication is happened in the two wires, you need to disable and enable the transmitter at the correct time. so that the proper communication should happen.

7. what is the difference between RISC and CISC controllers?
RISC CISC
Reduced instruction set computer is having less number of instructions. The RISC processors have simple instructions taking about one clock cycle. the cisc processor has complex instructions that take 2 to 15 clock cycles.
Performance is more focussed on software. Performance is more focused on hardware.
Most instrcutions are completed in 1 machine cycle. It has a memory unit to implement complex instructions.
- pipelining technique used to speed up RISC controllers. - multiple register set. - ecxecution time is very less - code expansion can be a problem - instruction decoding is simple - It does not require external memory for calculation - The most common risc processors are Alpha, ARC, AVR, MIPS, PA-RISC, Power Architecture, SPARC - RISC architecture is used in high end applications such as vedio processing, telecommunications and image processing. - it is having single register set - ecxecution time is very high - code expansion is not aproblem. - instruction decoding is complex - It requires external memory for calculation - examples of CISC processors are the System/360, VAX, PDP-11, Motorola 68000 family, AMD and Intelx86 CPU. - CISC architecture is used in low-end applications such a security system, home automation.

8. mention the required components of embedded system?

- Hardware -
  - microcontrollers
  - memory
  - timers
  - IO circuits
  - system application circuits, 
  - software
  -It checks the availabity of system memory
  - It checks the processor speed availability 
  - the need to limit the power lost when running the system continuously
- RTOS
It runs the processor as per scheduling and do the switching from one process to another

9. what are realtime embedded system?
Real time embedded system are systems that monitor, respond or control an external environment. This environment is connected to the system through actuators, sensors and input output interfaces.

10. what is Watchdog timer?
Watchdog timer will reset the system if it is not reloaded before watchdog timer expires. If the system do some malfunction then it would not reset the timer so the watchdog timer will reset the system.

Interrupts in Embedded System QA

Interrupts Q and A


1. What is interrupt?
	Interrupt is an input signal to the processor or microcontroller that an event needs immediate attention.
Interrupt is a request for the processor to stop the currently executing program and to execute the interrupt routine.
If the interrupt is accepted by the processor, it will stop the currently executing program, 
It will save the registers values, and return address of the program, then it will move to execute the interrupt 
program. After executing the interrupt routine, using return address it will start executing program which it was executing earlier program . 

There are two types of interrupts
Hardware interrupt:
It is a hardware signal to the cpu that it should be responded immediately. 
The cpu should save its current context and execute the inerrupt routine.

Software Interrupt:
Software interrupt is an software instruction which causes the inerrupt to occur.

2. What is iterrupt latency?
Interrupt latency is the time it take from when the interrupt is generated to the interrupt routine
started to execute. The interrupt latency is affected by microcontroller design.

Causes for interrupt latency time?
 - The interrupt requesting signal should be synchronised to cpu clock, it takes 3 clock time for interrupt signal to reach the 
   cpu core.
 - Typically the cpu complete the current instruction and then executes the isr. The time taken for the instruction to execute 
   is depending on the instruction it executes. If the instruction takes more time the latency time increases.
 - Memory system requires additional cycle states for wait states.
 - after executing the current instruction the cpu do the mode switch or pushes the register contents on to the stack.
   Arm controllers uses the mode switch which takes less time than pushing registers to the stack.
 - pipeline fill - most modern cpus are pipelined, if the interrupt is occured when the pipeline is filled then if the mode 
   switch is occured then extra cycles are needed to refill the pipline.
 - an Rtos disable interrupts to executes its api, it increases the latency time since it has to complete the executing the api 
   and then it will execute the interrupt.


3. How the interrupt routine should be?
    The interrupt routine size should be small as much possible as.
The isr size made small to make place for other isr to execute, otherwise the delay increases
for other ISRs to execute.



4. What are the different types of interrupt?

There are two types of interrupts
Hardware interrupt:
It is a hardware signal to the cpu that it should be responded immediately. 
The cpu should save its current context and execute the inerrupt routine.

Software Interrupt:
Software interrupt is an software instruction which causes the inerrupt to occur.

5. what is instruction pipeline?
   While executing the code the cpu loads the instructions to a pipeline, then it executes the instructions one by one.
 instructions are loaded as per the program flow.

6. what is interrupt priority?
  The interrupt priority is the priority set to each interrupt routine. 
  The high priority routine executes first and then the low priority interrupt will executes.
  If the low priority interrupt is executing, then if some high priority interrupt is requested, then the
  controller will stop executing the low priority interrupt and execute the high priority interrupt then
  executes the low priority interrupts.

7. what is interrupt vector table?
  Interrupt vector table is a addresses of the ISRs for the Interrupt handler to search Isrs.
  All interrupts are assigned with a number from 0 to 255. each of these interrupts are associated
  with aspecific interrupt address.
  Normally interrupt vector table is located in the first 1024 bytes 0000 to 03ff. Each interrupt takes 
  the 4 bytes address. so it needs 256 * 4 = 1024 bytes memory space.


8. what are different Triggering methods for interrupts?
   each interrupt can be triggered by either a logic level or edge 
  logic level can be low or high level
  edge triggered means rising edge or flaaing edge.
  Inerrupt can occur on rising edge or falling edge.
  Interrupt can occur on low or high logic level.

 
9. what are maskable interrupts?
   The ineterrupts in the microcontroller can be enable and disable using the register mask.
   To enable an interrupt a perticular bit has to be set in the mask register.
   To disable an interrupt a perticular  bit has to be reset in the mask register.
   the interrupt which are affected by mask register are called maskable interrupts.

10. what are non maskable interrupts?
   some interrupts cannot be disabled using interrupt mask, these interrupts are called Non maskable interrupts.

En-Query

Your Name*
Subject*
Phone Number*
Email Address*

Message*