Você está na página 1de 30

MAIN CONCEPTS IN C (INTERVIEW POINT OF VIEW):

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
1.  Storage allocators:
Ans : Every C variable has a characteristic called as storagte class. The storage class defines 
two characteristics of the variable : its Lifetime of a variable is the length of time it retains a 
particular value. The visibility of a variable defines which parts of a program will be able to 
recognize it . A variable may be visible in a block, a function, a file , a group of files, or an 
entire program. The variable's storage class determines whether the variable should b estored 
in the memory or in a register.
1. Automatic
2. External
3. Static
4. Register

1. Automatic:­     Automatic variables are nothing but the local variables. The scope of an 
automatic   variable   can   be   smaller   than   entire   function.,if   it   is   declared   from   within   a 
compound statement. They can be declared using the specifier  Auto., though the declaration 
is   not   necessary.   Any   variable   declared   within   a   function   or   code   block   auotmatically 
assumed to be of the class auto and the system sets aside the required memory area for that 
variable.
2. External:­ All global variables are declared in one file and same variables are declared as 
extern in all other files . The extern   keyword tells the compiler the types and names of the 
global variables being used without actually creating storage for them again. Although extern 
variable declarations can occur inside the same file as the global declaration , they are not 
necessary.
3.   Static:­  The  static  variables   are   permanent   variables   wihtin   their   own   functions   or 
files.Unlike global variables are not known outside their function or file , but they maintain 
their values between calls.This means that , if a function terminates and is then re­entered 
later, the  static  variables defined within that function would still retain their former values. 
The declaration begins with the static storage class designation. The compiler automatically 
assigns the default value of zero to any static variable, which is not initialized. The values of 
static variables are not re­initialized when a function is re­entered. The variables retain their 
previous values. Initialization take place once, at the bigning of the program.
4.Register:­ If a particular value is to be used often (for ex: the value that control loop), its 
storage class can be named as register. If the compiler then finds a free register, and if the 
machine's register are big enough to hold the variable,it is placed in thar register. Ohterwsie 
the compiler treats register variables as any other automatic variables, that is, it stores them in 
the memory. The keyword register must be used to define the register variables. The scope 
and initialization of the register variables are Identical to automatic variables,except for the 
location of storage. Register variables are local to a function and are also dynamic.Hence 
initialization of these variables is the responsibility of the programmer.The system does not 
initialize these variables.

2.  What is the d/w static function and general function?
Ans:    Satic functions  are recognized only within the program file and their scope does not 
extend outside the program file.It is used within that file only.It can't access out side of file, 
which file it is located.  
The scope of global function is through all the files of the program and it is the default 
storage class for functions.

3.  Explain the compilation process?
Ans:  Compilers translates source files containing high level language statement to object 
files   containing   machine   instructions   for   the   corresponding   high   level   statements.   The 
convertsion from C file to Object file will happen in various stages. We normally call this 
process as compilation.But it involves following four stages.
     1.preprocessing.
     2.compilation.
     3.Optimization.
     4.Assembling.

      Preprocessor   is   responsible   for   including   all   files   into   a   C   file,removing   the 
comments,expanding   all   the   macros(i.e#defines).Preprocessot   also   takecare   of   conditional 
compilation.
         Preprocessed output is given to the compiler.Compiler will generate  pseudo assembly 
language code.This assembly code is not corresponds to any microprocessor.
         The o/p of compiler pseudo code is given to optimization procee , which will optimize 
based   on   the   registers   of   microprocessor   ,and   finally   generates   assembly   language 
instructions for aparticular microprocessor.
         Finally the Assembler will take above generated assembly language file and converts it 
into a object file containing machine op­codes for the assembly instructions.

          1.HEADER   
          2.Text/Code  
          3. Data
          4. Reloc Info 
          5.  Symbol Info

The above various sections that could present inside an object file. The header sections 
gives the information about all the other sections Typically header tells what are the other 
sections   present   in   the   file,size   and   file   offset   position   of   each   section.   The   Text/Code 
sections contains the machine code for all the functions present in the source file. The Data 
section contains initial values of all the initialized data structures.

       The Relocation section contains the information about the locations, which need to be 
initialized   when   external   symbols   are   resolved   during   linking   process.Symbol   section 
contains name strings of variables and functions.
   
4.  Explain the exe image sections?
Ans:  The executable memory image contains following sections.
1. Text/Code
2. Data
3. BSS  (Block started by Symbol)
4. Heap
5. Stack

1. Every C function in the source file will be translated to a set of machine instructions 
and placed in the Text section. The address of a function will be the address of first 
instruction of the function.
2. All the initialized global and initialized static (inside a function) variables will be 
placed in the data section.
3.All an uninitialized global and static variables will be placed in the BSS.
4.All the local variables of a function will be allocated on the stack.
5. All the dynamic variables will be allocated on the heap.

5.   What is a function pointer?explain the callback function model?
Ans:  We can store addr of a function in a pointer,not for reading or writing but for executing 
that   function   these   are   called   "function   pointers".   Function   pointer   has   contain   some 
"opcode". These are registers the address of particular functions.

callback Model: we   store   our   function   addresses   in   a   library   function,then   the   library 


function   stores   our   function   addr   in   the   function   pointer.When   ever   we   call   that   library 
function,automatically it will be call our application function.This type of programming is 
called "callback model".

6. Give applications of function pointers?
 Ans: 
1.Signals
2.ISRs
3.Kernel systemcalls.     

7.  What is the d/w malloc() and calloc()?
Ans: The main differences  b/w malloc and calloc are 
1. parameters. :­ in malloc function we have a only one parameter. In calloc having the 
two parameters.
2. Allocation :­ The malloc allocated memory will contain a garbage cvalues. The  
calloc function automatically it fills th e null values what ever it may allocated 
memory.

8.  What is the d/w dynamic linking and static linking?
Ans:
Static Linking:­   It causes the copying of all library routines used in the program into the 
executable image. It is done at compile time.
Advantages:­
1. Makes the code more portable and does not require the presence of library on the 
system where it is running.
2. Static linking makes oraganising the information much easier. 
Disadvantages:­  It will consumes more disk space (hard disk) and memory (RAM).
Dynamic Linking:­  This is accomplished by placing the name of a sharable library in the 
exeimage. Actual linking of the library routines does not occur until the image is run, It will 
done at run time dynamically it will search the shared libraries and find out the external 
references. It can't copy the code into exe image.
Advantages:­
1. Multiple programms can share single copy of the library 
2. Improves multitasking efficiency and atleast paging aspect.
3. Simplifies some issues in application management.
4.Permits good architectural possibilities including packing and not updating.

9.  What is the d/w arrays and linked lists?
Ans:
 Arrays:­  1. Typically arrays are allocated statically , that is during compile time.
                  2. Memory allocated for all the elements of array will be contiguous.
     3. As all elements are in contiguous memory, direct access to any element is  
possible ,with the help of index.
4. Insertins and deletions into an array are not efficient operation.
Linked lists:­ 
1. Linked lists are typically used with dynamic allocation.
2. Memory for each element will be separate . (non contiguous).
3. Here access is sequential , one need to traverse through the linked list to
access any element.
4. Insertions and deletions of elements into linked list can be done efficiently.

10.  What is the void pointer?
Ans:  The void pointer is a generic pointer.Any pointer to an object may be converted to type 
void * without loss of information .If the result is converted back to the original pointer type, 
the original pointer is recovered.Void *   pointers with object pointers in assignments and 
relationsals, while requiring explicit casts for other pointer mixtures.

11. What do you mean by typedef and typecasting?
Ans:
Typedef:­ New data type name can be defined by using the keyword typedef . This does not 
create a new data class,but just defines a new name for an existing type. The advantage of a 
new name to the existing type improves the readability and thereby understandability of the 
code.   The   typedef   feature   is   particularly   convinient   when   defining   structures   since   it 
eleminates the need to repeatedly write struct tag whenever a structure is refereced.
Typecasting:­  Typecasting   allows   us   to   explicitly   convert   the   value   of   an   expression   or 
variable to a particular data type.
For Ex:­ when we want to use the value of some variable as an int at a few places and 
as a float at others . In such cases typecasting is the only solution.
12. Write a prog to add a node in single ll and doubble ll?
Ans:
13. Write a prog to delete a node from single ll and doubble ll?
Ans:

14. Work out on string operations?
Ans:
15. Work out on bitwise operations?
Ans:
16. Work out on some pointer and array concepts?
Ans:
17. Explain the Hashing technique?
Ans:
17. What are the uses of Queues?
Ans:  The operation in Queue is FIFO (First inFirst Out operation).
Queues   are   used   in   many   programming   situations.   One   of   the   most   common   in 
simulations. Queues are also used by the task scheduler of OS and for I/O buffering.
FIFO – Random access of any specific item is not allowed.
17. What are the uses of stacks?
Ans:  The operation in Stack is LIFO (Last in First Out operation).
Stacks are frequently used in System Software, including compilers and interpreters.
17.     What   is   the   difference   between   Single   Linked   List(SLL)   and   Double   Linked 
List(DLL)?
Ans:  SLL: It has one major drawback, that can't be transverse in reverse order. For this 
reason DLLs are usually used.
DLL:  This  list can  be  traverse in either direction. This simplified list management 
making insertions and deletions easier. Should one if the links become invalid, in list, the list
could be reconstructed by using the other.    

17. Explain the bitfields in structures?
Ans: A bit field must be a member of a structure or union. It defines how long, in bits, the 
field is to be.
Bit fields are frequently used when analyzing input from a h/w device.
Bit fields can be useful for a number of reasons.
1.  It storage is limited, you can store several boolean (True/False) variables in one
     byte.
2.  Certain devices transmit status information encoded into one or more bits within a
     byte.
3.  Cerain encryption routines need to access the bits with in a byte.
Although these tasks can be performed by using the bitwise operators; A bit field can
add more structure (and possibly efficiency) to your code.
18. What is the d/w stuctures and unions?
Ans:    We   can   consider   structures   as   compound   type   of   variables,   because   structure   can 
contain   various   type   elements,   including   arrays   and   structues.   A   structure   is   an   object 
consisting of named members of various types.
Allignments of fields in a structure:­ When structure contains different types of elements, 
the compiler tries to align these elements to their natural boundaries. Aligning to their natural 
boundaries gives efficient data transfer between CPU and Memory. Some Micro Processor 
will not allow accessing of elements which are not alligned to their natural boudaries.
Unions:­
A unoin is an object that contains , at different times, any one of several members of 
various types.
Unions   may   look   like   structures,   but   the   only(   and   important)   difference   is   that 
,memory for all the elements of union is starts with offset zero. That means memory for all 
the fields will be overlapped. So the size of union will be the size of largest element of the 
union. 
Uses of Unions:­ We may use unions for two purposes. One is to access onetype of variable 
as a different type and another one is unions will be ideal to pass to a functions, which accepts 
different types of input data, but we can access one at a time.
19. How to find the offset of structure members?
Ans: “ &((sturuct <name> *)0)­><member name> ”  This statement will prints the offset 
of the structure member.
          Ex: printf(“%d”,&((struct a *)0)­>ch);
20. What is a self­referential structure?
Ans: If a structure contains ,pointer to itself as an element in the staructure,it is called self­
referential structure. Self­referential structures are the best way of implementing the linked 
list.
21. List out some searching techniques?
Ans :
1. Linear searching.
2. Binary Searching.
3. Hashing.
22. what is the conditional compilation?
Ans : The ability to selectively compile parts of a program based on the truth of conditions 
tested in conditional directives that surround the code.parts of the program may be compiled 
conditionally,according to the following schematic syntax.

23. What is the macro?
Ans: A short peice of text,or template,that can be expanded into a longer text.

24. If headerfiles are included in single file twice.what happen?  if error is occured then 
how would you rectify that problem? 
Ans:  it will give the error. The conditional compilation is used for to rectify this type of 
errors.
     ex: header.h
         #ifndef HDR or #if !defined(HDR)
         #define HDR
         int i;
         int add(int);
         struct student st_s
         {
      int i;
      char name[10];
 }
   .....
       #endif
       
25. what is pointer?
Ans:  A pointer is a group of cells(often two or four) that can hold an address.

28.   what   is   the   difference   between   these   two   statements   #include"a.h"   and 
#include<a.h>?
Ans:
   #include<a.h>

   The preprocessor search starts at /usr/local/include,if search is fail then next it will starts at 
gcc libarary include files and /usr/local directories.

   #include"a.h"

   the preprocessor first it will checks current directory, if search is fails then,it will searches 
the defined path directories also.
   

26.   what is the volatile Keyword?
Ans:  A C keyword that indicates the value of a variable or constant can be changed at any 
time.This attribute is used for memory mapped I/O,shared memory applications,and other 
advanced      programming.
27.   what is preprocessing?
Ans: The preprocessr does the following jobs:
1.strips the comments.
  2.expands include files.
3.expands MACROs and replace symbolic constants
(simply put,the #define @);
      Adv: 1. Easy Write 2. Easy Read 3. Efficiency 4. Portable  and 5. Easy Modifications
     
28. Explain the inline function?
Ans:  By   preceeding   a   function   declaration   with   inline,   you   are   telling   the   compiler   to 
optimize calls to the function. Typically this means that the function code will be expanded 
inline rather than called.

29. What is a memory leak?
Ans: Memory leak is an amount of memory that has been rendered useless and inaccessible 
to the system.
     Ex:
   int main()
{
int i=0;
int *p;
for(i=0;i<10;i++)

  p=(int *)malloc(sizeof(int));
*p=10;
}
return 0;

LINUX 

1.   What is the d/w Linux systemcalls and API (Application Programming Interface) 
functions?
Ans:        Both   system   calls   and   APIs   are   normal   functions,   which   can   be   called   from 
application programs. There is no difference as for as usage is concerned.
But only difference is that, system call is implemented as a part of kernel. So whenever 
a system call is invoked, the process (which invoked system call) will switch from user mode 
to kernel mode and executes the system call and returns to the user mode once system call 
execution is completed.
API functions will execute in user mode only.
 
2.  What is the d/w User mode and Kernel mode?
Ans:    The word mode describes the change in the way the processor itself actually handles 
instructions and permissions.
Processes   running   in   User   space   are   not   allowed   to   access   directly   hardware   and 
execute   certain   instructions.   So   these   can   be   accessed   through   the   Kernel   space.User 
application programs are linked against their libraries, and those symbols are resolved at run 
time.
Kernel modules are linked against the kernel, and those module symbols are resolved 
when we attempt to load the module into kernel and these modules are resticted to access 
until those are loaded.

3.  What does fork() do?
Ans:
#include<sys/types.h>
#include<unistd.h>

pid_t fork(void);

The fork() system call is used to create a new process by the original process. The 
original process is called parent and the new process is called the child process.
For child process the return value of fork() will be zero, and for parent process the 
return value of fork() will be process  Id of the child.
The   things   inherited   by   the   child   from   parent   are   process 
credentials(real/effective/saved   UIDs   and   GIDs),   environment,   stack,   memory,   openfds, 
close­on­exec flags, signal handling settings, nice value, scheduler class, PGID,session ID, 
current working dir, root dir, file mode creation mask (umask), resource limits, controlling 
terminal.
The things unique to child are PID, different PPID, own copy of fds and dir streams, 
process, text, data and other memory locks are not inherited. process times, in the tms struct. 
resource utilizations are set to 0. pending signals initialized to the empty set. timers created by 
timer_create not inherited. asynchronous input or output operations not inherited.
4.  Give the major d/w fork() and vfork()?
Ans:    The basic difference between these two is that when a new process is created by with 
vfork() the parent process is temporarily suspended, and the child process might borrow the 
parent's address space. This will continue until the child process either exits or calls execve(), 
at which point the parent process continues.
This means that the child process of a vfork() must be careful to avoid unexpectedly 
modifyiing the variables of the parent process. In particular, the child process must not return 
from the vfork() and it must not call exit().(if it needs to call exit() then it must call _exit(); 
this is also true for the child of fork()). 
    
5.  What is the d/w exit() and _exit()?
Ans:    The differences between fork() and vfork() become more significant when fork(), and 
especially vfork() is used.
The basic difference between exit() and _exit() is that exit() performs clean­up related 
to user­mode constructs in the library, and calls user­supplied clean­up functions, whereas 
_exit() performs only the kernel clean­up for the process.
In the child branch of a fork(), it is normally incorrect to use exit(), because that can 
lead to stdio buffers being flushed twice, and temporary files being unexpectedly removed.
In the child branch of a vfork(), the use of exit() is even more dangerous, since it will 
affect the state of the parent process.

6.  What does exec() do?
Ans:     The exec() system call is useful to execute a new program by a process. A running 
program can call exec() system call to execute a new executable file by the same process.

7.   Does the PID of original process and the process created by exec() system call are 
equal or not? Why?
Ans: The procedd ID of both are same.   This is because the same process loads the given 
executable file and runs. 

8.   Why won't the original process execute its normal instructions after calling exec() 
system call? 
Ans: Once   exec()   is   successful,   no   instructions   after   exec()   statement   will   be   executed. 
Because this program will be over written with a new program.
9.  When do we use exec() system call?
Ans:     The exec() system call is very useful to run a different program by a child process. 
After fork() the child process runs the same program as that of parent. But we canuse exec() 
system call make child process to run a different executable program.

10.  What are the various flavors of exec() system call?
Ans: The various flavors of exec() system calls are
int execl(const char *pathname, const char arg0,.../*(char *)0 */);
int execv(const char *pathname, char *argv[]);
int   execle(const   char   *pathname,   const   char   arg0,.../*(char   *)0   ,char   *const 
envp[]*/);
int execve(const char *pathname, char *argv[],char *const envp[]);
int execlp(const char *filename, const char arg0,.../*(char *)0 */);
int execvp(const char *filename, char *const argv[]);

11.  What is the functionality of select, pselect and poll system calls?
Ans: The select(is BSD syscall), pselect and poll(is an artifact of Sys V STREAMS) system 
calls are used to monitor more than one connection/fd/stream at a time.
select, pselect and poll systemcalls do the same thing, just differently. They examine a 
set of fds to see if specific events are pending on any, and then optionally wait for a specified 
time for an event to happen.
These system calls mainly based on the creation of set of fds. FD set is a data structure 
which is useful for creating set of fds. To perform operations on this FD set the following 
macros are used.

FD_ZERO(fd_set *fdset);
FD_SET(int fd,fd_set *fdset);
FD_CLR(int fd,fd_set *fdset);
FD_ISSET(int fd,fd_set *fdset);

12.  Explain select() system call?
Ans:
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>

int select(int n, fd_set *readfds, fd_set *writefds, fd_set *expectfds, struct timeval 
*timeout);
The select() system call wathes the three independent sets of descriptors. Where n is the 
highest numbered descriptor in any of the three sets, plus 1.The fds listed in readfds will be 
watched to see if a read will not block, the fds listed in writefds will be watched to see if a 
write   will   not   block,   the   fds   listed   in   expected   fds   will   be   watched   for   exceptions.   To 
manipulate these sets above macros can be used. Timeout is an upper bound on the amount of 
time elapsed before select returns. It may be zero, causing select to return immediately.  (This 
is useful for polling). If timeout is NULL(no timeout), select can block indefinitely.

13.  Explain pselect() system call?
Ans:
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>

int pselect(int n, fd_set *readfds, fd_set *writefds, fd_set *
expectfds,   const   struct   timespec   *timeout,   const   sigset_t 
*sigmask);

sigmask is a pointer to a signal mask, if it is NULL, then pselect first replaces the 
current signal mask by the one pointed to by sigmask, then does the select function, and then 
restores the original signal mask again.

The idea of pselect() is that if one wants to wait for an event, either   a   signal   or   a   fd, 


an atomic test is needed to prevent race conditions. (Suppose the signal handler sets a global 
flag and returns. Then a test of this global flag followed by a call of select() could hang 
indefinitely if the signal arrived just after the test but just before the call. On the otherhand, 
pselect   allows   one  to   first   block   signals,  handle  the  signals  that   have  come in,   then call 
pselect() with the desired sigmask avoiding the race.) Since LINUX does not have a pselect() 
system call today, the current glibc2 routine still contains this race.

14.  Explain poll() system call?
Ans:
#include<sys/poll.h>
int poll(struct pollfd *ufds, unsigned int nfds, int timeout);
poll is a variation on the theme of select. It specifies an array of nfds structures of type
struct pollfd
{
int fd;
short events;
short revents;
};
and a timeout in milliseconds. A negative value means infinite timeout. The field fd 
contains a file descriptor for an open file. The field events is an input parameter, a bitmask 
specifying the events the application is interested in. The field revents is an output parameter, 
filled by the kernel with the events that actually occured, either of the type requested, or one 
of the types POLLERR or POLLHUP or POLLNVAL.(These three bits are meaning less in 
the events field and set in the revents field whenever the correaponding condition is true.) 
If   none   of   the  events   requested   has   occured  for   any  of   the  fds,   the  kernel   waits  for   the 
timeout(milli seconds) for one of the events to occur. 

15.  What is the difference between select() and pselect() system calls?
Ans:        The   functionality   of   these   two   systemcalls   are   identical,   but   there   exists   some 
differences. Those are
1 The select function uses a timeout that is a struct timeval (with seconds and micro 
seconds),while pselect uses a struct timespec (with seconds and nano seconds).
2. The select function may update the timeout parameter to indicate how much time 
was left. The pselect function  does not change this parameter.
3.The select function has no sigmask parameter, and behaves as pselect called with 
NULL sigmask. 

16.  Explain the copy on write concept?
Ans: Many current implementations don't perform a complete copy of the parent's data,stack 
and heap since  a fork is often followed by an exec. Instead a technique called copy­on write 
(COW) is used. These regions are shared by the parent and child and have their changed by 
the kernel to read­only. If their process tries to modify these regions , the kernel then makes a 
copy of that piece of memory only, typically a “page” in avirtual memorysystem.

17.  What is the d/w threads and processes?
Ans:    If a process contains only one path of execution which starts with main function and 
completes its execution when the main function returns or an exit() system call is called by 
any other function then this path of execution is called thread. 
Since it starts with main function then that thread is called main thread.If a process 
contains multiple threads (i.e more than one execution path) created by main thread, then all 
these threads run concurrently with the main thread. All these threads share the same process 
environment. That means process address space containing text, data, heap is common to all 
the threads. All opened file descriptors also common to all threads. But each  thread will have 
its own stack and registers.

18.  What is the d/w threads in LINUX and tasks in RTOS?
Ans:        Similar   to   threads,   tasks   in   RTOS   also   share   the   same   address     space,   but   the 
difference is that the address space shared by LINUX   process is logical or virtual address 
space and the address space shared by the RTOS is physical address space. It does not use 
virtual address space for efficiency and
simpllicity.

19. What is the d/w pipe and fifo?
Ans: Both pipe and fifo are used  for inter process communication.The major differences 
between   them   are   Pipe   can   be   used   only   for   the   related   processes   like   parent   and   child 
processes.  
Pipe can be created as follows.
#include<unistd.h>

int pipe(int filedes[2]);

FIFO can be accessed by any process, because it got a name, and appears as a file in the 
file system. So any process can open a FIFO if it got access permissions.

FIFO can be created as follows.
#include<sys/types.h>
#include<unistd.h>

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

20. List out the IPC mechanisms?
Ans:    Traditional Unix supports two types of IPC mechanisms.
1. Pipes
2. Named pipes or FIFOs
System V IPC supports three types of IPC mechanisms.
1. Messagequeues
2. Semaphores
3. Shared memory  

 
21. Which one is the best IPC mechanism? Why?
Ans:    The best IPC mechanism is Shared memory. This is because of it will reduce the no of 
read and write calls. 

22. Explain semaphores? Give some examples?
Ans: The system V semaphore is a communication object which can hold any number of 
tokens starting from 0(no tokens) to some maximum limit. Normally when semaphore object 
is created, the initial token count will be specified.
The operations on the semaphores performed by a process are Taking a token from the 
semaphore.Giving a token ton the semaphore.
    This simple concept semaphores can be used for synchronization and mutual exclusion 
between   processes.Synchronization   is   provided   by   the   binary   semaphores   and   mutual 
exclusion is provided by the mutex semaphores.

23. Difference b/w binary and mutex semaphores?
Ans: Binary   semaphores   are   used   for   providing   synchronization   between   producer   and 
consumer processes. Initially the semaphore is created with zero tokens in it. The consumer 
process   will   block   on   the   semaphore   for   a   token   until   producer   produceses   the   data. 
Whenever  producer  produces  the data and sends  a token to the semaphore the consumer 
process   wakes   up   and   consumes   data  supplied   by  the  producer  process.Mutual   exclusion 
semaphores are used for resource sharing.For example, if all processes require a resource 
printer, then this can be accessed by only one process at a time.
If   the   first   process   uses   a   printer   after   that   only   remaining   processes   access   that 
resource one after another.This can be achieved by using mutual exclusion semaphores.Here 
the first process takes a token, uses that resource and gives a token to the semaphore. Then 
the next process which waits on this semaphore takes a token, uses that resource.Thus all 
processes uses that resource.

24.  Why System V semaphores are more complex than POSIX/RTOS semaphores?
Ans: Because of the following reasons System V semaphores are more complex.
1.   System   V   semaphore   calls   allow   to   create   just   not   one   semaphore   but   set   of 
semaphores and  other semaphore system calls also operate ont multiple semaphores at a 
time.
2. System V semaphores also support taking and giving multiple tokens in a single 
system  call.
3. System V semaphore, provide a mechanism nwaiting for a token count to become 
zero. 

NETWORKING

1.  List out the system calls of UDP and TCP flow?
Ans:
     udpsrv:                 udpcli:
     ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
     socket()                socket()
       |                              |
     bind()                       |             
       |                              |
     recvfrom()           sendto()
       |                              |
     sendto()               recvfrom()
       |                              |
     close()                  close()
     
     tcpSrv:                  tcpCli 
     ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
     socket()                 socket()
        |                               |
      bind()                  connect()
        |                             |
     listen()                     |
        |                            |
     accept()                   |
        |                        send()
      recv()                     |
        |                            |
      send()                  recv()
        |                            |
      close()                 close() or shutdown() or abort()
 
 
2.  Explain the connect and accept system calls?
Ans:
Connect:­
The Connect function is used by the TCP client to establish a connection with a TCP 
server.
int connect(int sockfd,const struct sockaddr *srvadr,socklen_t addrlen);
In   the   case   of   a   TCP   socket   ,   the   connect   function   initiates   TCP's   three­way 
handshaking.   The   function   returns   only   when   the   connection   is   established   or   an   error
occurs.
     
Accept:
         Accept() is called by the tcp server to return the next completed connection from the 
front   of   the   completed   connection   queue.if   the   completed   connection   queue   is   empty,the 
process is put to sleep(assuming the default blocking socket).
int accept(int sockfd,struct sockaddr *cliaddr,socklen_t *addrlen);
      The addrlen return value contains the actual no.of bytes stored by the kernel in the 
socket address structure. If accept() is successful , its return value is a brand new descriptor 
that   was   automatically   created   by   the   kernel.   This   new   descriptor   refers   to   the   TCP 
connection with the client.The first argument of accept is a listen sockfd, and the return value 
is a connected sockfd.The listen sockfd then exists for the life time of the server.When the 
server is finished serving given client the connected socket is closed.

3.  How to create a daemon server?
Ans:   Most of the server applications will run as daemon processes.Daemon processes will 
run in background mode,they will not have any controlling terminal.Daemon processes are 
different from the applications you run in background mode by giving '&' at hte end of the 
command.When you run applications in background mode, these background applications are 
still associated with controlling terminal and if you logout from terminal,all the background 
processes belonging to this terminal also get killed.
steps are:

         1.fork()   : The new process is guarateed not to be a process group leader.So this step 
required,         the next step setsid(), if its fails if you are a process group leader.
         2.setsid() : The setsid function to create a new session and become a process group and 
session                   group   leader   and   this   session   has   not   yet   acquired   a   controlling 
terminal our process         now has no controlling terminal,which is good thing for 
daemons. 
         3.chdir("/") : to ensure that our process does not keep any dir in use.
                 4.umask() :  so that we have complete control over the permissions of anything we 
write.
     ex:
         int daemon_init(void)
         {
           pid_t pid;
           if(pid=fork())<0)
             return ­1;
           else if(pid!=0)
             exit(0);
           setsid();
           chdir("/");
           umask(0);
           return 0;
        }

4.  What is the d/w UDP and TCP?
Ans:
UDP:­  UDP   is   simple   Connection   less,   Datagram­oriented,Unreliable   and   transport   layer 
 protocol. It does not support any flow control and error control.
 Eg:­ It just like a post office(real time ex).
    
TCP :­   TCP is Connection­oriented and Reliable protocol.It supports the flow control and 
error      control by using SeqNo and Ack fields in the Tcp header.
Eg:­ Telephone connection(real time ex).

5.  How to identify created socket is either UDP socket or TCP socket?
Ans:       The created socket is differentiated by type and protocol fields in socket system 
call.These   two   parameters   are   to   identify   the   communication   type(SOCK_DGRAM   , 
SOCK_STREAM etc) and specific protocol type(udp­17,tcp­6 etc.)

6.  What is a port? What r the types of ports?
Ans:    It is a 16­bit number which is used to identify a process in TCP/IP protocol suite.
            Well Known ports   : 0           ­   1023
            Ephemeral ports      : 1023     ­    49151 (registered ports)
            Private ports            :  49152  ­    65535

7.  What is the use of bind system call?
Ans: The Bind function assigns a local protocol address to a socket.The protocol address is 
the combination of either a 32­bit Ipv4 address or 128­bit IPv6 address along with a 16­bit 
TCP or UDP         port number.

8.  What r the ranges of private addresses in classful adressing?
Ans:    The ranges of private addresses r
        ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
       |   class   range                  blocks      |
        ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
         class A  10.0.0 1
         class B  172.16 to 172.31            16
         class C  192.168.0 to 192.168.255            256
     
9. What is a mask? Why do we need a mask?
Ans:       For IPv4, a mask is a 32­bit number that gives the first address in the block (the 
network address) when AND ed with an address in that block.

11. What is a subnet mask?
Ans:    It is a mask which is used to find out a subnet address.

12. How to find subnetid in IPv4 addresses?
Ans:    If the destination address and the subnet mask r given, by applying AND operation on 
them, subnet address is obtained.

19. How do u say that IP is a Best effort protocol?
Ans:       Ip is a Best effort protocol because it will make every effort to always transmit a 
datagram   and   also   datagrams   will   not   be   just   discarded.   However,   the   delivery   of   the 
datagram to the destination is not guaranted.

11. What is the purpose of identification field in IP header?
Ans:       The identification field in IP header contains a sequence number which is used to 
uniquely identify and assemble the different fragments of a datagram.
12. What is the purpose of TTL field in IP header?
Ans:    The TTL field is used to limit the lifetime of a datagram and to prevent the indefinite 
looping of datagrams.
Initially,   the   TTL   field   contains   some   counter   value   set   by   the   source   host.   Each 
gateway that processes this datagram decreases the TTL value by one.  When the TTL value 
reaches zero then it discards that datagram.

The typical value for the TTL field is 32 or 64.

13. What is IP fragmentation?
Ans:    The breaking up a single IP datagram into two or more IP datagrams of smaller size is 
called IP fragmentation.

13. What is the purpose of fragmentation ofset field in IP header?
Ans:    This field is used to hold the starting address of a fragment.

15. Why do we require fragmentation?
Ans:    Every transmission medium has a limit on the maximum size of a frame(MTU) it can 
transmit.   As   IP   datagrams   are   encapsulated   in   frames,   the   size   of   IP   datagram   is   also 
restricted. If the size of an IP datagram is greater than this limit, then it must be fragmented. 

17. Explain flags field in IP header?
Ans:   This is a 3­bit field. 
The first bit is reserved.
The second bit is called the do not fragment bit. 
If its value is 1, the machine must not fragment the datagram. 
If its value is 0, the datagram can be fragmented if necessary  
The third bit is called the more fragment bit.
If its value is 1, it means the datagram is not the last one,
there are more fragments after this one.
If its value is 0, it means this is last one.

18. What is the purpose of cheksum field in IP header?
Ans:       This field is used for error detection. The cheksum protects against corruption that 
may occur during the transmission of a packet. It contains redundant information added to the 
packet.
20. List out the uses of UDP? 
Ans:       UDP is suitable for a process that requires simple request­response communication 
with little concern flow and error control. (Eg: It is not usually used for a process such as FTP 
that needs to send bulk data.)//It is suitable for a process with internal flow and error­control 
mechanisms. (Eg: TFTP process includes flow and error control. so it can use UDP)// It is a 
suitable transport protocol for multicasting.
It is used for management process such as SNMP.
It is used for some route updating protocols such as RIP.
(Routing Information Protocol)

21. How do u say that TCP is a Connection­oriented protocol?
Ans:        TCP   is   a   Connection­oriented   protocol   beacause   it   creates   a   virtual   connection 
between  two  TCPs  to  transfer  data by using connection­oriented services  like connection 
stablishment, connection termination and connection reset.

22. How do u say that TCP is Reliable  protocol?
Ans:    TCP is a Reliable Protocol because it provides acknowledgement mechanism to check 
the safe and sound arrival of data. 
23. What r the services provided by TCP?
Ans:    The services provided by TCP are
1. Process­to­Process communication
           2. Stream delivery service
3. Full­duplex service
4. Connection­oriented service
5. Reliable service
24. What r the features provided by TCP?
Ans:    The features of TCP are
1. Numbering system
2. Error control
3. Flow control
4. Congestion control
25. How do u achieve flow control in TCP?
Ans:       To achieve flow control in TCP , window size, SeqNo, and ACK No fileds are 
required.
26. Explain sillywindow syndrome in TCP?
Ans:       It is a serious problem that can arise in sliding window operation when either the 
sending   application   program   sends   data   slowly   or   the   receiving   application   program 
consumes   data   slowly   or   both.   Any  of   these   situations  sending  data  is   very  mall,  which 
reduces the efficiency of the operation. for example: If TCP sends a segment containing 
only one byte of data (it means that a 41­byte datagram which is equal to 20 bytes of TCP 
header, 20 bytes of IP header and 1 byte of user data) then the capacity of the network used 
inefficiently. 

27. How do u achieve errorcontrol in TCP?
Ans:     Error control includes mechanisms for detecting corrupted segments, lost segments, 
out­of­order segments, and duplicated segments. It also includes a mechanism for correcting 
errors after detecting them. Error correction and detection in TCP is achieved through the use 
of three simple tools: Cheksum , Acknowledgement, and Time­out.

28. Explain the purpose of Time­wait timer in TCP?
Ans: Time­wait timer in TCP is used for Connection termination.

29. What is meant by congestion? How do u control congestion in TCP?
Ans:     Congestion in a network may occur if the load on the network(i.e the no.of packets 
sent to the network) is greater than the capacity of the network(i.e the no.of packets that a 
network can han dle).
i.e Excessive network or internet traffic causing a general degradation of service is called 
congestion.
The strategies used to control congestion are:
 1. Slow start algorithm(exponential increase):
        In this algorithm, the size of the congestion window increases exponentially until 
it  reaches a threshold.
 2. Congestion avoidance algorithm(additive increase):
In this algorithm, the size of the congestion window increases additively until  
congestion is detected.
 3. Congestion detective(multiplicative decrease):
   ­­ If detection is by time­out, a new slow start phase starts.
   ­­ If detection is by three ACKs, a new congestion avoidance phase starts.    

30. Why do we reuire SeqNo and ACK Fields in TCP header?
Ans:    SeqNo is a 32­bit number assigned to the first byte of data contained in the segment. 
Since TCP is a Stream transport protocol, to ensure connectivity, each byte to be transmitted 
is numbered. The SeqNo tells the destination which byte in this sequence comprises the first 
byte  in   the  segment.   During   connection  establishment   each   party  uses   a   random   number 
generator to create an initial SeqNo, which is usually different in each direction.

ACK field is a 32­bit field defines the byte number that the receiver of the segment is 
expecting to receive from the other party.

31. What is the need of Window size in TCP header?
Ans:    It is a 16­bit number field used to control the flow of data so that the destination does 
not become overwhelmed with the data.

31. Explain the Sliding Window Protocol Technique?
Ans:    It is a technique which is used to control the flow of transfering data before receiving 
an acknowledgement in TCP. 

33. What is the purpose of psuedoheader in checksum calculation?
Ans:    Both UDP and TCP include a 12­byte pseudo­header with the UDP datagram or TCP 
segment just for the checksum computation. The purpose is to let UDP or TCP double check 
that the data has arrived at the correct destination. i.e That IP has not accepted a datagram or 
segment that is not addressed to this host, and that IP has not given UDP a datagram or TCP 
segment  that is for another upperlayer.

34. Explain connection establishment in TCP?
Ans:    The connection establishment in TCP is called Three­way handshaking.

For example an apllication pgm called client wants to make a connection with another 
application pgm called server, using TCP as the Transport layer protocol then the procedure is 
asfollows.
1. The client sends the first segment, a SYN segment in which only the SYN flag is set. This 
segment   is   for   synchronization   of   sequence   numbers.   Here   the   client   chooses   a   random 
number   as   the   first   sequence   number   and   sends   this   to   server.   This   number   is   called 
ISN(Initial Sequence Number).
A SYN segment cannot carry data, but it consumes one sequence number.
   
2. The server sends the second segment, a SYN+ACK segment with two flags set: SYN and 
ACK.     This segment has a dual purpose. First it is a SYN segment for communication in 
other direction.    Next it acknowledges the SYN segment received from a client by setting 
ACK flag.
A SYN+ACK segment cannot carry data, but it consumes one sequence number.
   
3. The client sends the third segment, an ACK segment with ACK flag set. The sequence 
number in this segment is the same as one in the SYN segment.

An ACK segment, if carrying no data, consumes no sequence number.
   
35. Explain connection termination in TCP?
Ans:        The   connection   termination   in   TCP   is   possible   with   two   options   Three­way 
handshaking and four­way handshaking with half­close  option.

Three­way handshaking:
 1. In a normal situation, if a client TCP wants to terminate a connection with server TCP, it 
sends a first segment, FIN segment to server TCP in which FIN flag set. This segment may 
include last chunk of data or it may be a control segment.

A FIN segment consumes one sequence number if it does not carry data.

2. The server TCP after receiving the FIN segment, it sends FIN+ACK segment to client TCP 
with two flags set: FIN and ACK. This segment may include last chunk of data or it may be a 
control segment. This segment has a dual purpose. First it acknowledges the FIN segment 
received from a client TCP by setting ACK flag. Next it sends a  FIN segment for closing the 
connection in other direction. 

A FIN+ACK segment consumes one sequence number if it does not carry data.

3. The client sends the third segment, an ACK segment with ACK flag set. The sequence 
number in this segment is the same as one in the SYN segment. This segment contains the 
ACK number which is one plus the sequence number received from the server.  

An ACK segment, if carrying no data, consumes no sequence number.

36. Explain half­open and half­close in TCP?
Ans:   
 Half­close:
In TCP, one end stops sending data while still receiving data is called  a half­close.      

Normally,   half­close   connection   is   initiated   by   a   client.The   client   half­closes   the 


connection by sending a FIN segment  to the server. The server accepts the half­close by 
sending ACK segment to the client. The data transfer from the client to the server stops. The 
server, however, can still send data. When the server has sent all the processed data and if it 
wants to terminate connection then it sends FIN segment to client which is acknowledged by 
sending an ACK segment from the client to the server.
After half­close connection, data can travel from server to client not from client to 
server. This can be identified by the seqNo which is in the second segment called ACK 
segment. This segment does not consume any seqNo. In this case the client receives seqNo 
lessthan one what it expects.

Half­open:
A   TCP   connection   is   said   to   be   half­open   if   one   end   has   closed   or   aborted   the 
connection without the knowledge of other end.

The common cause of a half­open connection is when a client host is powered off, 
instead of terminating the client application and then shutting down the client host.

37. When do u send a segment with reset bit set in TCP?
Ans:    In the following cases the segment will be sent with reset flag set.
1. Denying a connection
2. Aborting a connection
3. Terminating an idle connection

40. What is the need of PUSH flag in TCP?
Ans:    If PUSH flag will be set in sending TCP then there is no need to wait for the window 
to be filled. It sends that segment immediately. 

41. What is the need of URG flag and Urgentpointer field in TCP?
Ans:       If the sending application program wants to send a piece of data to be read out of 
order by the receiving application program, the URG flag will be set and the address of urgent
data is hold by the Urgentpointer field.  

42. What is the d/w  gateway and router?
Ans:    Gateway is a connecting device operating at all five layers of internet model.Router is 
a connecting device operating at the first three layers of the OSI model or TCP/IP model.

43. What is the d/w repeater and amplifier?
Ans:       An amplifier is a device which is used to amplify a signal.It cannot discriminate 
between the intended signal and noise, it amplifies equally everything fed into it.A repeater is 
a connecting device that extends distance of a signal can travel by regenerating the signal.A 
repeater does not amplify the signal, it regenerates the signal. When it receives a weakened or 
corrupted signal, it creates a copy, bit for bit, at the original strength.

44. What is the d/w bridge and router?
Ans:       A bridge is a Two­Layer(Physical, datalink)switch.It connects segments of a LAN 
together. So there is no need to change the physical address of a packet.

A   router   is   a   Three­Layer(Physical,   datalink,   and   network)   switch.   It   connects 


independent LANs or WANs to create an internet. So it is necessary to change the physical 
address of a packet.

45. What is the d/w repeater and router?
Ans:
Repeater:
1. A repeater is a One­Layer(Physical)switch. 
2. It connects segments of a LAN together. 
3. It does not change the physical address of a packet.

Router:
1. A router is a Three­Layer(Physical, datalink, and network)switch.
2. It connects independent LANs or WANs to create an internet.
3. It changes the physical address of a packet.

46. What is the d/w bridge and repeater?
Ans: A bridge is a Two­Layer(Physical, datalink)switch. It has filtering capability.

A repeater is a One­Layer(Physical)switch.
It has no filtering capability. (Filtering Capability means it just forwards every bit in a 
packet. It does not drop the packet)
 
47. What is the d/w switch, router, and repeater?
Ans:    A switch is a device which is used to connect communication lines together.
A router is a device which is used to connect independent LANs or WANs.

A repeater is a device which is used to connect segments of a LAN.

47. Explain simultaneous open and simultaneous close in TCP?
Ans:        In   simultaneous   open,   both   applications   issue   active   opens.   This   is   a   very   rare 
situation in which there is no client or server; communication is between two peers that know 
their local port numbers. In this case both ends send SYN segment almost at the same time 
and changes their state from CLOSED to SYN­SENT. After receiving SYN segment each end 
sends SYN+ACK segment to other end and changes their state from SYN­SENT to SYN­
RCVD. Thus these two ends open the connection. This connection establishment involves a 
four­way handshaking.

In simulataneous close, if both ends issue active close at the same time, each end sends 
FIN segment to other end and changes their state from ESTABLISHED to FIN­WAIT1. After 
receiving FIN segment each end sends ACK segment to other end and chnages their state 
from FIN­WAIT1 to CLOSING state.After receiving ACK segment each end goes to TIME­
WAIT state which is required for both ends because each end has sent an ACK that may get 
lost.

48. List out the some standard server port numbers?
Ans:
 UDP server port numbers          TCP server port numbers
        
Name port Name port

DNS 53 DNS 53
Bootps 67 FTP 20(data)
Bootpc 68 FTP 21control)
TFTP 69 TELNET 23
SNMP 161 SMTP 25
SNMP 162(trap) BOOTP 67
HTTP 80

49. What is the d/w close, shutdown and abort?
Ans:
close:
#include<unistd.h>
int close(int fd);

close systemcall closes a file descriptor, so that it no longer refers to any file and may 
be reused. Any locks held on the file, it was associated with, and owned by the process, are 
removed.If fd is the last copy of a particular file descriptor the resources associated with it are 
freed, if the descriptor is the last reference to a file which has been removed by using unlink() 
the file is deleted.

shutdown:
#include<sys/socket.h>
int shutdown(int s, int how);

The shutdown call causes all or part of full­duplex connection on the socket associated 
with s to be shutdown. If how is SHUT_RD further receptions will be disallowed. If how is 
SHUT_WR   further   transmissions   will   be   disallowed.If   how   is   SHUT_RDWR   further 
receptions and transmissions  will be disallowed.

abort:
#include<stdlib.h>
void abort(void);

The abort() function causes abnormal program termination unless the signal SIGABRT 
is   caught   and   the   signal   handler   does   not   return.   If   the   abort()   function   causes   program 
termination, all open streams are closed and flushed. If the SIGABRT is blocked or ignored, 
the abort() function will still override it.

50. What r the sublayers in DLL?
Ans: 
The sublayers in Data Link Layer :
LLL Logical Link Layer
MAC Media Access Control

51. What r the protocols implemented in DLL?
Ans: 
The protocols implemented in Data Link Layer :
PPP Point to Point protocol
LCP Link Control Protocol
NCP Network Control Protocol
PPoE Point to Point over Ethernet

Você também pode gostar