Linkers and loaders: http://www.iecc.com/linker/
Dynamic linking and loading: http://www.iecc.com/linker/linker10.html
Blog Archive
-
▼
2007
(55)
-
►
Apr
(48)
- Socket Programming
- Pthreads
- Virtual Memory Management
- How a system call is implemented?
- Inter-process communication
- How malloc has been implemented (brk system call)?
- Linux Modules - How are they linked dynamically?
- Proc File System
- fork, vfork, copy-on-write and clone
- CPU Scheduling -- Different types of CPU schedulin...
- Signals (System V and POSIX)
- How mapping from virtual address address to physic...
- setuid program (real and effective user ids)
- Exceptions, traps, interrupts and signals
- Processor execution levels
- Process Address Space
- Unix/Linux File System Layout
- Salient points about Unix/Linux
- Big Endian versus Little Endian
- Semaphore, Mutex, Conditional variable, Spin lock
- Segmentation Fault and Bus Error
- wait() system call
- Bottom half
- Linux time keeping - Timer interrupt, jiffies, xtime
- Position Independent Code (PIC)
- kmalloc/kfree and vmalloc/vfree
- Static versus shared objects
- How many processes will be created-- fork?
- Can we get return value from exec system call?
- How does profiling code works? -- processor debug ...
- ptrace - how does it work?
- Record locking
- GNU Linux pthreads
- How do you use RSA for both authentication and sec...
- Unix/Linx bootupand login
- What are various problems unique to distributed da...
- cooperative,preemption,non preemption
- Puzzles
- Write system call that prints stack trace at that ...
- DMA (Direct Memory Access)
- Real Time Systems
- Comparison of IOS and General Purpose OS like Linux
- Operating Systems I/O Structure
- Linux - Process Scheduling
- Deadlock avoidance and prevention
- Porting from 32 bit OS to 64 bit OS
- Sign extension
- How to make an application daemon
-
►
Apr
(48)
Unix Programming Quiz
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Signals are a form of interprocess communication. Which of the following statements does not describe a limitation of signals?
A-The number of user definable signals is limited.
B-They contain no data, only indication of an event.
C-On some systems, two identical signals arriving at the same time are not resolved correctly.
D-You cannot send a signal to more than one process simultaneously.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A daemon process can be described by all of these statements except which?
A-It is detached from a controlling terminal.
B-It responds to requests that arrive through some means of interprocess communication.
C-It must run with root permissions.
D-It is usually is in operation for an extended period of time.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a process ends, what always happens?
A-Open file descriptors are closed.
B-Memory used by that process code segment goes on the free list.
C-Shared memory segments are removed.
D-The parent process is notified.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The classic use of semaphores is to coordinate the usage of a resource common to two or more processes. How else could you accomplish this?
A-use signals
B-use shared memory
C-use a daemon process
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/dev/null is bit bucket. What is returned when /dev/null is read?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the X Window System, which of the following is true about the window manager?
A-It is a client application that maintains the "look and feel" of other client application's windows.
B-It is the same as the X server.
C-It must run on the same machine as the X server.
Signals are a form of interprocess communication. Which of the following statements does not describe a limitation of signals?
A-The number of user definable signals is limited.
B-They contain no data, only indication of an event.
C-On some systems, two identical signals arriving at the same time are not resolved correctly.
D-You cannot send a signal to more than one process simultaneously.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A daemon process can be described by all of these statements except which?
A-It is detached from a controlling terminal.
B-It responds to requests that arrive through some means of interprocess communication.
C-It must run with root permissions.
D-It is usually is in operation for an extended period of time.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a process ends, what always happens?
A-Open file descriptors are closed.
B-Memory used by that process code segment goes on the free list.
C-Shared memory segments are removed.
D-The parent process is notified.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The classic use of semaphores is to coordinate the usage of a resource common to two or more processes. How else could you accomplish this?
A-use signals
B-use shared memory
C-use a daemon process
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/dev/null is bit bucket. What is returned when /dev/null is read?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the X Window System, which of the following is true about the window manager?
A-It is a client application that maintains the "look and feel" of other client application's windows.
B-It is the same as the X server.
C-It must run on the same machine as the X server.
Take Linux Programming Test
Test Outline
AutoConf/AutoMake, Makefiles
Cross Platform Installation
Program installation
C Programming
Data Structures
Files and Devices
Functions/Subroutines
Libraries
Memory Allocation
Terminals/User Interfaces
C++
Libraries
Object Oriented Programming
Debugging programs
Core files
GDB
Memory Leaks
Linux Programming Concepts
IPC
Pipes and Redirection
Processes
Semaphores, Shared memory, Message Queues
Sockets
Threads
Platform Independence
CPU/OS Architecture
Libraries
Revision Control
Checking items in/out of a CVS server
Resolving conflicts with CVS
Using CVS
RPC/CORBA
Concepts
Network Programming
X Programming
Communication
GTK+
Motif/LessTif
TCL/TK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Which one of the following header files will allow you to use the 'pipe' function to create a pipe for IPC?
Choice 1
kernel.h
Choice 2
fifo.h
Choice 3
unistd.h
Choice 4
pipe.h
Choice 5
stdio.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a GTK+ based program, which one of the following portions is executed if no events are available?
Choice 1
gtk_sleep ()
Choice 2
gtk_wait ()
Choice 3
main ()
Choice 4
gtk_event_idle ()
Choice 5
gtk_main ()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Question In which one of the following ways does CVS determine a conflict?
Choice 1
CVS calls GCC with -O9 which checks for conflicts in C code.
Choice 2
CVS connects to a central CVS server which provides conflict tracking information specific to the programming language in use.
Choice 3
CVS's understanding of conflicts is strictly textual.
Choice 4
CVS doesn't look for conflicts
Choice 5
It contains a database of programming language BNF. If the changes fundamentally change the way the program operates, it is flagged as a conflict.
Linux Programming (General), Question 3 of 40
Take a 15 minute break AFTER this question
© Copyright 2007 Brainbench All Rights Reserved.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following libraries will halt a program that uses more memory than is requested in a malloc?
Choice 1
BugCatcher
Choice 2
xmalloc
Choice 3
malloc_debugger
Choice 4
chkmem
Choice 5
ElectricFence
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following functions is will allow you to prevent race conditions in threaded applications?
Choice 1
pthread_mutex_lock(), pthread_mutex_unlock()
Choice 2
pthread_join(), pthread_detach()
Choice 3
pthread_create()
Choice 4
pthread_attr_setschedpolicy()
Choice 5
pthread_attr_setschedparam()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following sets the gdb debugger set to print values in hex?
Choice 1
set output-hex 1
Choice 2
set output-radix 16
Choice 3
set output-radix 15
Choice 4
set output-mode 16
Choice 5
set output-mode hex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You are writing a hex editing program that needs to run on several platforms.
Question Based on the above scenario, which one of the following is the platform independent way of clearing bit 2 from int n in C?
Choice 1
n &= 0xfffb;
Choice 2
n = 0x12;
Choice 3
n &= ~(1<<2);
Choice 4
n &= 0x04;
Choice 5
n == 0x02;
Linux Pro
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When "make" is run without any additional parameters, which one of the following targets is executed?
Choice 1
No targets get executed. "Make" requires a target.
Choice 2
The last target listed
Choice 3
The target labeled "all"
Choice 4
The target labeled "default"
Choice 5
The first target listed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Display *display;
display = XOpenDisplay(NULL);
Question Based on the above scenario, which one of the following is returned by XOpenDisplay if the connection fails?
Choice 1
A struct
Choice 2
0
Choice 3
A pointer
Choice 4
-1
Choice 5
NULL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You are selecting a user interface library for a client program that needs to compile and run in Linux, as well as in MS-Windows.
Question Based on the above scenario, which one of the following libraries will allow you to display a graphical user interface in both Linux and MS-Windows environments?
Choice 1
KDE libraries
Choice 2
Stdlib libraries
Choice 3
wxWindows libraries
Choice 4
WinLib libraries
Choice 5
GNOME libraries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following functions is used to print output in a kernel module?
Choice 1
printk
Choice 2
kprint
Choice 3
printf
Choice 4
printd
Choice 5
prints
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What is main reason for splitting Linux interrupt handlers into a top half and a bottom half?
Choice 1
There is no reason to split Linux interrupt handlers.
Choice 2
To allow the handler to schedule time consuming operations to occur at a later time when interrupts have been enabled.
Choice 3
To separate the handler into a relatively small segment of code that stays resident and a larger optional segment which can be swapped in and out of main memory as needed.
Choice 4
To separate the user-space and kernel-space portions of the interrupt handler; thereby reducing the potential damage poorly written code can have on the rest of the system.
Choice 5
To encourage code reuse by providing a layer of abstraction between the interface to a handler and its functional parts.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following header files should be included in order for a C program to use Lesstif functions?
Choice 1
lesstif.h
Choice 2
xlib.h
Choice 3
motif.h
Choice 4
lt.h
Choice 5
Xm/Xm.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code
test1: main.o foo.o bar.o
gcc -o myapp main.o foo.o bar.o
main.o: main.c a.h
gcc -c main.c
foo.o: foo.c a.h b.h
gcc -c 2.c
bar.o: bar.c b.h c.h
gcc -c bar.c
$ make
Makefile:2: *** missing separator. Stop.
Question The above code isn't working properly, which one of the following is a likely cause?
Choice 1
Not specifying the proper dependencies
Choice 2
Specifying improper parameters for gcc
Choice 3
Make can't find gcc
Choice 4
Using the colon to separate the target from the dependencies
Choice 5
Using spaces for the indented lines
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How is a doubly linked list different from a singly linked list?
Choice 1
A doubly linked list can be used for process queuing in a round robin scheme; a singly linked list can only be used to create B-trees.
Choice 2
A doubly linked list is made using a struct; a singly linked list is made using an array.
Choice 3
A doubly linked list can be thought of as a virtual doughnut structure; a singly linked list is a virtual circle structure.
Choice 4
A doubly linked list holds a list of double precision reals; a singly linked list holds standard precision reals.
Choice 5
A doubly linked list has pointers to go forward and backward; a singly linked list can only go forward.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following is the fastest form of IPC?
Choice 1
Named Pipes
Choice 2
Process Pipes
Choice 3
Shared Memory
Choice 4
Message Queue
Choice 5
Semaphores
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways is a CVS conflict handled?
Choice 1
A warning is issued; the working copy is updated with the repository copy with markings detailing the overlap. Anyone can correct the overlap.
Choice 2
CVS doesn't monitor for conflicts.
Choice 3
CVS avoids conflicts by locking a section of code during the checkout process. The programmer works on that specific portion of code and commits it to the repository when complete. At that time, other programmers can check out that section of code.
Choice 4
A warning is issued; the latest code is merged with the working copy with overlaps marked. The programmer is expected to resolve the conflict and re-commit.
Choice 5
CVS automatically resolves conflicts using a transaction tracking system to monitor all changes.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following is the most common form of semaphore?
Choice 1
Decimal semaphore
Choice 2
Hex semaphore
Choice 3
Unary semaphore
Choice 4
Multitasking semaphore
Choice 5
Binary semaphore
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which two assembly sources are usually included with the Linux kernel to handle differences between platforms?
Choice 1
bbootsect.s and vmlinux.lds.S
Choice 2
head.S and entry.S
Choice 3
reg_u_sub.S and div_Xsig.S
Choice 4
kernel.asm and io.asm
Choice 5
mm.asm and memalloc.asm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following indicates the format of the curses WINDOW function?
Choice 1
WINDOW newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
Choice 2
WINDOW &newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
Choice 3
WINDOW *newwin(struct *screendef)
Choice 4
WINDOW *newwin(long int num_of_lines, long int num_of_cols, int start_y, int start_x);
Choice 5
WINDOW *newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a variable is created in C, which one of the following is its initial value?
Choice 1
It must be defined upon creation.
Choice 2
\0
Choice 3
Random
Choice 4
Null
Choice 5
Empty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What needs to be done to debug a program using strace?
Choice 1
Compile the program with optimization level 3 using -O3
Choice 2
Compile the program with the strace header file included
Choice 3
Compile with '-gstrace'
Choice 4
Compile the program with '--strace'
Choice 5
Nothing, any program can be watched with strace.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The TCP/IP protocol is big-endian and the Intel x86 processor is little-endian.
Question Based on the above scenario, which one of the following should be done to bytes sent to the TCP/IP stack?
Choice 1
Nothing. The kernel takes care of issues related to the architecture.
Choice 2
Include netintet/in.h and use htonl, htons, ntohl, and ntohs to perform the conversion.
Choice 3
Include endian.h and use swapendian, pushendian, popendian, and memcp to perform the conversion.
Choice 4
Include convert.h to perform the needed conversions.
Choice 5
Include net/ethernet.h and use ethertype_ip, ethertype_tcp, and ether_hdr_len to read from or write to the ethernet device.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following command line switches is useful in creating makefile dependency lines?
Choice 1
autoconf's -dep switch
Choice 2
find's -dep switch
Choice 3
make's -j5 switch
Choice 4
diff's -newdep switch
Choice 5
gcc's -MM switch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following describes how a semaphore can be used?
Choice 1
To allow recursive access to a critical section.
Choice 2
To share memory with multiple processes.
Choice 3
To allow cooperative shared access to a critical section by providing shared update facilities.
Choice 4
To allow shared access to a critical section by multiplexing and backtracking.
Choice 5
To allow exclusive access to a critical section, one process at a time.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With regard to curses, which one of the following does refresh(); do?
Choice 1
It resets the data structure that represents the screen.
Choice 2
It displays the data structure representing the screen to stdscr.
Choice 3
It clears the screen.
Choice 4
It re-draws the screen to get rid of errant characters from a dialup connection.
Choice 5
It clears the keyboard buffer.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following programs allows rapid development of GTK user interface statements for C and C++ programs?
Choice 1
gdv
Choice 2
Gimp
Choice 3
Glade
Choice 4
guile
Choice 5
TCL/TK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following library calls is used to allocate memory in C and initialize it to zero?
Choice 1
alloca()
Choice 2
calloc()
Choice 3
realloc()
Choice 4
malloc()
Choice 5
bzero()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways are lock files handled in Linux?
Choice 1
They are mandatory in nature. The kernel provides exclusive access to a process.
Choice 2
They are advisory in nature, but the kernel provides multiplex access via time offsets
Choice 3
They are advisory in nature. Your program handles them.
Choice 4
Lock files can be used for serial devices only.
Choice 5
They are mandatory in nature, but are handled in user space.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You need to design a distributed application that works with big-endian and little-endian systems.
Question In which one of the following ways does CORBA help to complete the above scenario?
Choice 1
By using IPC structures to relay data
Choice 2
By using middle-endian data
Choice 3
By marshaling and unmarshalling parameters and return values
Choice 4
By using a sockets based transport to move raw data between different networks
Choice 5
By moving data processing to a subprocess, creating an abstraction of the data that is unaffected by host byte order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main(argc, argv)
int argc;
char *argv[];
{/* main prog here */
}
Question Based on the above code, which one of the following describes *argv[0]?
Choice 1
A count of the number of command line arguments
Choice 2
A pointer to a null terminated string holding the name of the program
Choice 3
The name of the program
Choice 4
The first command line item the user passed, given after the program name
Choice 5
A stack pointer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#define SCSI_IOCTL_SEND_COMMAND 1
struct sdata {
int inlen;
int outlen;
char cmd[256];
} scsi_cmd;
void unlockdoor( int fd )
{
scsi_cmd.inlen = 0;
scsi_cmd.outlen = 0;
scsi_cmd.cmd[0] = 0x1e;
scsi_cmd.cmd[1] = 0;
scsi_cmd.cmd[2] = 0;
scsi_cmd.cmd[3] = 0;
scsi_cmd.cmd[4] = 0;
scsi_cmd.cmd[5] = 0;
if (ioctl(fd,SCSI_IOCTL_SEND_COMMAND,(void *)&scsi_cmd))
perror("eject: door unlock ioctl error");
}
Question The above code is from the eject command. Which one of the following values is returned by ioctl if the error message is NOT printed?
Choice 1
0
Choice 2
256
Choice 3
1
Choice 4
-1
Choice 5
0x1e
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
r = c ? 2 : 3;
Question In the code listed above, to which one of the following values would be assigned to r if c==0 in C?
Choice 1
undefined
Choice 2
null
Choice 3
0
Choice 4
2
Choice 5
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using Internet sockets, which one of the following levels of service does "streams" provide?
Choice 1
Connectionless, reliable, two way byte stream
Choice 2
Connectionless, non-reliable, one way byte stream
Choice 3
Local, inter process, reliable byte stream
Choice 4
Sequenced, reliable, two way byte stream
Choice 5
ASCII byte stream
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following authentication methods is often used to check items in and out of an open-source project when using CVS?
Choice 1
pserver
Choice 2
xserver
Choice 3
serverd
Choice 4
cvsserver
Choice 5
rcsserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You want to assure platform independent code between Linux and MS-Windows.
Question In which one of the following ways should a file be opened in order to ensure the above scenario?
Choice 1
Add a 'b' to the mode string.
Choice 2
Add a ;c' to the mode string.
Choice 3
Add a 'p' to the mode string.
Choice 4
Add a 'w' to the mode string.
Choice 5
Add a 'z' to the mode string.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int n;
Question Based on the above code, which one of the following statements is TRUE about an integer variable in C?
Choice 1
A value of 0 is false; all others are true.
Choice 2
A value of -1 is false; all others are true.
Choice 3
A value of 1 is true; all other values are false.
Choice 4
A value of 0 is true; all other values are false.
Choice 5
Integer values are neither true nor false.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const MAXAVGSIZE = 200;
struct input_data {
double input_data<200>;
};
typedef struct input_data input_data;
program AVERAGEPROG {
version AVERAGEVERS {
double AVERAGE(input_data) = 1;
} = 1;
} = 22855;
Question Which one of the following methods should be used to process the above code?
Choice 1
gcc -O4
Choice 2
make
Choice 3
g++
Choice 4
gcc -C
Choice 5
rpcgen
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To which one of the following values do external variables initialize in C?
Choice 1
0
Choice 2
UNDEF
Choice 3
-1
Choice 4
Random
Choice 5
1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways is geometry management important in Motif/Lesstif?
Choice 1
To allow physical device characteristics to be determined prior to the layout stage
Choice 2
To allow mouse based window control
Choice 3
To allow fonts and windows to be scaled while maintaining a reasonable layout.
Choice 4
To allow coordinates to be input into a drawing program
Choice 5
To allow exact placement of widgets regardless of the display device
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AutoConf/AutoMake, Makefiles
Cross Platform Installation
Program installation
C Programming
Data Structures
Files and Devices
Functions/Subroutines
Libraries
Memory Allocation
Terminals/User Interfaces
C++
Libraries
Object Oriented Programming
Debugging programs
Core files
GDB
Memory Leaks
Linux Programming Concepts
IPC
Pipes and Redirection
Processes
Semaphores, Shared memory, Message Queues
Sockets
Threads
Platform Independence
CPU/OS Architecture
Libraries
Revision Control
Checking items in/out of a CVS server
Resolving conflicts with CVS
Using CVS
RPC/CORBA
Concepts
Network Programming
X Programming
Communication
GTK+
Motif/LessTif
TCL/TK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Which one of the following header files will allow you to use the 'pipe' function to create a pipe for IPC?
Choice 1
kernel.h
Choice 2
fifo.h
Choice 3
unistd.h
Choice 4
pipe.h
Choice 5
stdio.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a GTK+ based program, which one of the following portions is executed if no events are available?
Choice 1
gtk_sleep ()
Choice 2
gtk_wait ()
Choice 3
main ()
Choice 4
gtk_event_idle ()
Choice 5
gtk_main ()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Question In which one of the following ways does CVS determine a conflict?
Choice 1
CVS calls GCC with -O9 which checks for conflicts in C code.
Choice 2
CVS connects to a central CVS server which provides conflict tracking information specific to the programming language in use.
Choice 3
CVS's understanding of conflicts is strictly textual.
Choice 4
CVS doesn't look for conflicts
Choice 5
It contains a database of programming language BNF. If the changes fundamentally change the way the program operates, it is flagged as a conflict.
Linux Programming (General), Question 3 of 40
Take a 15 minute break AFTER this question
© Copyright 2007 Brainbench All Rights Reserved.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following libraries will halt a program that uses more memory than is requested in a malloc?
Choice 1
BugCatcher
Choice 2
xmalloc
Choice 3
malloc_debugger
Choice 4
chkmem
Choice 5
ElectricFence
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following functions is will allow you to prevent race conditions in threaded applications?
Choice 1
pthread_mutex_lock(), pthread_mutex_unlock()
Choice 2
pthread_join(), pthread_detach()
Choice 3
pthread_create()
Choice 4
pthread_attr_setschedpolicy()
Choice 5
pthread_attr_setschedparam()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following sets the gdb debugger set to print values in hex?
Choice 1
set output-hex 1
Choice 2
set output-radix 16
Choice 3
set output-radix 15
Choice 4
set output-mode 16
Choice 5
set output-mode hex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You are writing a hex editing program that needs to run on several platforms.
Question Based on the above scenario, which one of the following is the platform independent way of clearing bit 2 from int n in C?
Choice 1
n &= 0xfffb;
Choice 2
n = 0x12;
Choice 3
n &= ~(1<<2);
Choice 4
n &= 0x04;
Choice 5
n == 0x02;
Linux Pro
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When "make" is run without any additional parameters, which one of the following targets is executed?
Choice 1
No targets get executed. "Make" requires a target.
Choice 2
The last target listed
Choice 3
The target labeled "all"
Choice 4
The target labeled "default"
Choice 5
The first target listed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Display *display;
display = XOpenDisplay(NULL);
Question Based on the above scenario, which one of the following is returned by XOpenDisplay if the connection fails?
Choice 1
A struct
Choice 2
0
Choice 3
A pointer
Choice 4
-1
Choice 5
NULL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You are selecting a user interface library for a client program that needs to compile and run in Linux, as well as in MS-Windows.
Question Based on the above scenario, which one of the following libraries will allow you to display a graphical user interface in both Linux and MS-Windows environments?
Choice 1
KDE libraries
Choice 2
Stdlib libraries
Choice 3
wxWindows libraries
Choice 4
WinLib libraries
Choice 5
GNOME libraries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following functions is used to print output in a kernel module?
Choice 1
printk
Choice 2
kprint
Choice 3
printf
Choice 4
printd
Choice 5
prints
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What is main reason for splitting Linux interrupt handlers into a top half and a bottom half?
Choice 1
There is no reason to split Linux interrupt handlers.
Choice 2
To allow the handler to schedule time consuming operations to occur at a later time when interrupts have been enabled.
Choice 3
To separate the handler into a relatively small segment of code that stays resident and a larger optional segment which can be swapped in and out of main memory as needed.
Choice 4
To separate the user-space and kernel-space portions of the interrupt handler; thereby reducing the potential damage poorly written code can have on the rest of the system.
Choice 5
To encourage code reuse by providing a layer of abstraction between the interface to a handler and its functional parts.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following header files should be included in order for a C program to use Lesstif functions?
Choice 1
lesstif.h
Choice 2
xlib.h
Choice 3
motif.h
Choice 4
lt.h
Choice 5
Xm/Xm.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code
test1: main.o foo.o bar.o
gcc -o myapp main.o foo.o bar.o
main.o: main.c a.h
gcc -c main.c
foo.o: foo.c a.h b.h
gcc -c 2.c
bar.o: bar.c b.h c.h
gcc -c bar.c
$ make
Makefile:2: *** missing separator. Stop.
Question The above code isn't working properly, which one of the following is a likely cause?
Choice 1
Not specifying the proper dependencies
Choice 2
Specifying improper parameters for gcc
Choice 3
Make can't find gcc
Choice 4
Using the colon to separate the target from the dependencies
Choice 5
Using spaces for the indented lines
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How is a doubly linked list different from a singly linked list?
Choice 1
A doubly linked list can be used for process queuing in a round robin scheme; a singly linked list can only be used to create B-trees.
Choice 2
A doubly linked list is made using a struct; a singly linked list is made using an array.
Choice 3
A doubly linked list can be thought of as a virtual doughnut structure; a singly linked list is a virtual circle structure.
Choice 4
A doubly linked list holds a list of double precision reals; a singly linked list holds standard precision reals.
Choice 5
A doubly linked list has pointers to go forward and backward; a singly linked list can only go forward.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following is the fastest form of IPC?
Choice 1
Named Pipes
Choice 2
Process Pipes
Choice 3
Shared Memory
Choice 4
Message Queue
Choice 5
Semaphores
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways is a CVS conflict handled?
Choice 1
A warning is issued; the working copy is updated with the repository copy with markings detailing the overlap. Anyone can correct the overlap.
Choice 2
CVS doesn't monitor for conflicts.
Choice 3
CVS avoids conflicts by locking a section of code during the checkout process. The programmer works on that specific portion of code and commits it to the repository when complete. At that time, other programmers can check out that section of code.
Choice 4
A warning is issued; the latest code is merged with the working copy with overlaps marked. The programmer is expected to resolve the conflict and re-commit.
Choice 5
CVS automatically resolves conflicts using a transaction tracking system to monitor all changes.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following is the most common form of semaphore?
Choice 1
Decimal semaphore
Choice 2
Hex semaphore
Choice 3
Unary semaphore
Choice 4
Multitasking semaphore
Choice 5
Binary semaphore
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which two assembly sources are usually included with the Linux kernel to handle differences between platforms?
Choice 1
bbootsect.s and vmlinux.lds.S
Choice 2
head.S and entry.S
Choice 3
reg_u_sub.S and div_Xsig.S
Choice 4
kernel.asm and io.asm
Choice 5
mm.asm and memalloc.asm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following indicates the format of the curses WINDOW function?
Choice 1
WINDOW newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
Choice 2
WINDOW &newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
Choice 3
WINDOW *newwin(struct *screendef)
Choice 4
WINDOW *newwin(long int num_of_lines, long int num_of_cols, int start_y, int start_x);
Choice 5
WINDOW *newwin(int num_of_lines, int num_of_cols, int start_y, int start_x);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a variable is created in C, which one of the following is its initial value?
Choice 1
It must be defined upon creation.
Choice 2
\0
Choice 3
Random
Choice 4
Null
Choice 5
Empty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What needs to be done to debug a program using strace?
Choice 1
Compile the program with optimization level 3 using -O3
Choice 2
Compile the program with the strace header file included
Choice 3
Compile with '-gstrace'
Choice 4
Compile the program with '--strace'
Choice 5
Nothing, any program can be watched with strace.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The TCP/IP protocol is big-endian and the Intel x86 processor is little-endian.
Question Based on the above scenario, which one of the following should be done to bytes sent to the TCP/IP stack?
Choice 1
Nothing. The kernel takes care of issues related to the architecture.
Choice 2
Include netintet/in.h and use htonl, htons, ntohl, and ntohs to perform the conversion.
Choice 3
Include endian.h and use swapendian, pushendian, popendian, and memcp to perform the conversion.
Choice 4
Include convert.h to perform the needed conversions.
Choice 5
Include net/ethernet.h and use ethertype_ip, ethertype_tcp, and ether_hdr_len to read from or write to the ethernet device.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following command line switches is useful in creating makefile dependency lines?
Choice 1
autoconf's -dep switch
Choice 2
find's -dep switch
Choice 3
make's -j5 switch
Choice 4
diff's -newdep switch
Choice 5
gcc's -MM switch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following describes how a semaphore can be used?
Choice 1
To allow recursive access to a critical section.
Choice 2
To share memory with multiple processes.
Choice 3
To allow cooperative shared access to a critical section by providing shared update facilities.
Choice 4
To allow shared access to a critical section by multiplexing and backtracking.
Choice 5
To allow exclusive access to a critical section, one process at a time.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With regard to curses, which one of the following does refresh(); do?
Choice 1
It resets the data structure that represents the screen.
Choice 2
It displays the data structure representing the screen to stdscr.
Choice 3
It clears the screen.
Choice 4
It re-draws the screen to get rid of errant characters from a dialup connection.
Choice 5
It clears the keyboard buffer.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following programs allows rapid development of GTK user interface statements for C and C++ programs?
Choice 1
gdv
Choice 2
Gimp
Choice 3
Glade
Choice 4
guile
Choice 5
TCL/TK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following library calls is used to allocate memory in C and initialize it to zero?
Choice 1
alloca()
Choice 2
calloc()
Choice 3
realloc()
Choice 4
malloc()
Choice 5
bzero()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways are lock files handled in Linux?
Choice 1
They are mandatory in nature. The kernel provides exclusive access to a process.
Choice 2
They are advisory in nature, but the kernel provides multiplex access via time offsets
Choice 3
They are advisory in nature. Your program handles them.
Choice 4
Lock files can be used for serial devices only.
Choice 5
They are mandatory in nature, but are handled in user space.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You need to design a distributed application that works with big-endian and little-endian systems.
Question In which one of the following ways does CORBA help to complete the above scenario?
Choice 1
By using IPC structures to relay data
Choice 2
By using middle-endian data
Choice 3
By marshaling and unmarshalling parameters and return values
Choice 4
By using a sockets based transport to move raw data between different networks
Choice 5
By moving data processing to a subprocess, creating an abstraction of the data that is unaffected by host byte order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main(argc, argv)
int argc;
char *argv[];
{/* main prog here */
}
Question Based on the above code, which one of the following describes *argv[0]?
Choice 1
A count of the number of command line arguments
Choice 2
A pointer to a null terminated string holding the name of the program
Choice 3
The name of the program
Choice 4
The first command line item the user passed, given after the program name
Choice 5
A stack pointer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#define SCSI_IOCTL_SEND_COMMAND 1
struct sdata {
int inlen;
int outlen;
char cmd[256];
} scsi_cmd;
void unlockdoor( int fd )
{
scsi_cmd.inlen = 0;
scsi_cmd.outlen = 0;
scsi_cmd.cmd[0] = 0x1e;
scsi_cmd.cmd[1] = 0;
scsi_cmd.cmd[2] = 0;
scsi_cmd.cmd[3] = 0;
scsi_cmd.cmd[4] = 0;
scsi_cmd.cmd[5] = 0;
if (ioctl(fd,SCSI_IOCTL_SEND_COMMAND,(void *)&scsi_cmd))
perror("eject: door unlock ioctl error");
}
Question The above code is from the eject command. Which one of the following values is returned by ioctl if the error message is NOT printed?
Choice 1
0
Choice 2
256
Choice 3
1
Choice 4
-1
Choice 5
0x1e
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
r = c ? 2 : 3;
Question In the code listed above, to which one of the following values would be assigned to r if c==0 in C?
Choice 1
undefined
Choice 2
null
Choice 3
0
Choice 4
2
Choice 5
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using Internet sockets, which one of the following levels of service does "streams" provide?
Choice 1
Connectionless, reliable, two way byte stream
Choice 2
Connectionless, non-reliable, one way byte stream
Choice 3
Local, inter process, reliable byte stream
Choice 4
Sequenced, reliable, two way byte stream
Choice 5
ASCII byte stream
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which one of the following authentication methods is often used to check items in and out of an open-source project when using CVS?
Choice 1
pserver
Choice 2
xserver
Choice 3
serverd
Choice 4
cvsserver
Choice 5
rcsserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You want to assure platform independent code between Linux and MS-Windows.
Question In which one of the following ways should a file be opened in order to ensure the above scenario?
Choice 1
Add a 'b' to the mode string.
Choice 2
Add a ;c' to the mode string.
Choice 3
Add a 'p' to the mode string.
Choice 4
Add a 'w' to the mode string.
Choice 5
Add a 'z' to the mode string.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int n;
Question Based on the above code, which one of the following statements is TRUE about an integer variable in C?
Choice 1
A value of 0 is false; all others are true.
Choice 2
A value of -1 is false; all others are true.
Choice 3
A value of 1 is true; all other values are false.
Choice 4
A value of 0 is true; all other values are false.
Choice 5
Integer values are neither true nor false.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const MAXAVGSIZE = 200;
struct input_data {
double input_data<200>;
};
typedef struct input_data input_data;
program AVERAGEPROG {
version AVERAGEVERS {
double AVERAGE(input_data) = 1;
} = 1;
} = 22855;
Question Which one of the following methods should be used to process the above code?
Choice 1
gcc -O4
Choice 2
make
Choice 3
g++
Choice 4
gcc -C
Choice 5
rpcgen
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To which one of the following values do external variables initialize in C?
Choice 1
0
Choice 2
UNDEF
Choice 3
-1
Choice 4
Random
Choice 5
1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In which one of the following ways is geometry management important in Motif/Lesstif?
Choice 1
To allow physical device characteristics to be determined prior to the layout stage
Choice 2
To allow mouse based window control
Choice 3
To allow fonts and windows to be scaled while maintaining a reasonable layout.
Choice 4
To allow coordinates to be input into a drawing program
Choice 5
To allow exact placement of widgets regardless of the display device
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Linux - Process Scheduling

Chaptor 10: Process Scheduling
From book Understanding the Linux KernelBy Daniel P. Bovet & Marco Cesati
Comparison of IOS and General Purpose OS like Linux
IOS Features
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The whole Operating System runs as a single process and kernel mode.
Monolithic
No Virtual Memory
Everything Runs in RAM
Cooperative Multitasking
Process relinquishes CPU on its own by calling --
Scheduler - Multilevel Priority queues
Four priority queues - CRITICAL, HIGH, NORMAL, LOW
Static priorities - decided at the time of creation of the process.
Can be changed thru cli/function call.
CPU HOG Message --- Trace from timer interrupt.....
Quantum 2 ms
Watchdog 2 minutes
I wrote function to print Stack trace from a interrupt handler---------.
---> Made some changes in timers - AVL tree and Timer wheel
---> Timers --- Timer wheeels
What are the advantages/disadvantages of cooperative multitasking
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Process does not have to worry about critical sections.
All processes have to be responsible. One process caught in loop will hog the CPU.
Is Cisco IOS an RTOS? Not really. Its is not hard real time system. It has
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
No virtual memory
Priority based scheduling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The whole Operating System runs as a single process and kernel mode.
Monolithic
No Virtual Memory
Everything Runs in RAM
Cooperative Multitasking
Process relinquishes CPU on its own by calling --
Scheduler - Multilevel Priority queues
Four priority queues - CRITICAL, HIGH, NORMAL, LOW
Static priorities - decided at the time of creation of the process.
Can be changed thru cli/function call.
CPU HOG Message --- Trace from timer interrupt.....
Quantum 2 ms
Watchdog 2 minutes
I wrote function to print Stack trace from a interrupt handler---------.
---> Made some changes in timers - AVL tree and Timer wheel
---> Timers --- Timer wheeels
What are the advantages/disadvantages of cooperative multitasking
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Process does not have to worry about critical sections.
All processes have to be responsible. One process caught in loop will hog the CPU.
Is Cisco IOS an RTOS? Not really. Its is not hard real time system. It has
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
No virtual memory
Priority based scheduling
Real Time Systems
Introduction
Characteristics of real time operating system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Process scheduling - Priority based
Resource access control - Aim is to keep the duration of every priority inversion bounded from above.
Memory allocation/deallocation - Memory fragmentation may cause indeterminism. Use preallocated buffers.
Does real-time mean as fast as possible?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The term "real-time" does not mean "as fast as possible" but rather "real-time" demands consistent, repeatable, known timing performance.
Resource access control (Chapter 8 of book Real Time Systems by Jane W. S. Liu)
Nonpreemptive Critical Section (NPCS) Protocol
Priority-Inheritance Protocol
Basic Priority-Ceiling Protocol
Differences between priority-inheritance protocols and priority-ceiling protocol
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Priority-inheritance rule of these are essentially same
The priority-inheritance protocol does not prevent deadlock.
Priority-ceiling blocking is sometimes referred to as avoidance blocking - blocking caused by the priority ceiling rule is the cost for avoidance of deadlocks among jobs.
Priority-inheritance is greedy while later is not.
Few Terms/Concepts
Priority-inversion
Priority ceiling of a resource
Priority ceiling of a system
Books/Articles/Links
"Tutorial on Hard Real-Time Systems", edited by John A. Stankovic and Krithi Ramamritham, IEEE Computer Society reprint series, Computer Society order number 819
Basic Concepts of Real-Time Operating Systems
Comp.RealTime NewsGroup FAQ
http://www.faqs.org/faqs/realtime-computing/faq/
Books --
Characteristics of real time operating system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Process scheduling - Priority based
Resource access control - Aim is to keep the duration of every priority inversion bounded from above.
Memory allocation/deallocation - Memory fragmentation may cause indeterminism. Use preallocated buffers.
Does real-time mean as fast as possible?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The term "real-time" does not mean "as fast as possible" but rather "real-time" demands consistent, repeatable, known timing performance.
Resource access control (Chapter 8 of book Real Time Systems by Jane W. S. Liu)
Nonpreemptive Critical Section (NPCS) Protocol
Priority-Inheritance Protocol
Basic Priority-Ceiling Protocol
Differences between priority-inheritance protocols and priority-ceiling protocol
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Priority-inheritance rule of these are essentially same
The priority-inheritance protocol does not prevent deadlock.
Priority-ceiling blocking is sometimes referred to as avoidance blocking - blocking caused by the priority ceiling rule is the cost for avoidance of deadlocks among jobs.
Priority-inheritance is greedy while later is not.
Few Terms/Concepts
Priority-inversion
Priority ceiling of a resource
Priority ceiling of a system
Books/Articles/Links
"Tutorial on Hard Real-Time Systems", edited by John A. Stankovic and Krithi Ramamritham, IEEE Computer Society reprint series, Computer Society order number 819
Basic Concepts of Real-Time Operating Systems
Comp.RealTime NewsGroup FAQ
http://www.faqs.org/faqs/realtime-computing/faq/
Books --
Puzzles
Puzzle #1
Three identical boxes, one containing two black marbles, one containing a black marble and a white marble, and a third containing two white marbles, are placed side by side on a table. Originally each box had a label on it describing its contents, but so meone has mixed up the labels so that each one is incorrect (i.e., no label is correct). The problem is to determine the contents of each box by a sampling process: choosing one box, blindly removing one marble from it, and repeating the process as m any times as it takes to positively infer the contents of each box. What sampling procedure would you use to identify the contents of each box with the fewest number of draws?
Puzzle #2
A commuter is in the habit of arriving at his suburban station each evening at exactly five o'clock. His chauffeur always meets the train and drives him home. One day he takes an earlier train, arriving at the station at four. The weather is pleasant, so instead of telephoning home he starts walking along the route always taken by his driver. They meet somewhere along the way. He gets into the car and they drive home, arriving at the house ten minutes earlier than usual. Assuming that the chauffeur always drives at a constant speed, and had left just in time to meet the five o'clock train, can you determine how long the commuter walked before he was picked up?
Puzzle #3
The following conversation took place in a home supply/hardware type store like Lowe's or National Home Center:
"How much will one cost?"
"Seventy five cents," replied the clerk.
"And how much will twelve cost?"
"A dollar fifty."
"Okay, I'll take nine hundred and twelve."
"That will be two dollars and twenty five cents."
What was the customer buying?
Puzzle #4
An explorer walks one mile due south, turns and walks one mile due east, then walks one mile due north and finds himself back where he started. He then shoots a bear. What color is the bear? The age-old answer is white because he must have started at t he North Pole. Is there anywhere else on earth where one could walk a mile south, a mile east, and a mile north and be back at the exact same spot? Explain.
Puzzle #5
A carpenter, working with a power saw, wishes to cut a wooden cube, three inches on a side, into 27 one-inch cubes. He can easily do this by making six cuts through the cube, keeping the pieces together in the cube shape. Can he reduce the number of nec essary cuts by rearranging the pieces after each cut? Explain.
Puzzle #6
A cylindrical hole exactly 6 inches long has been drilled straight through the center of a solid sphere. What is the volume remaining in the sphere?
Puzzle #7
You have ten stacks of coins, each consisting of ten half-dollars. One entire stack is counterfeit, but you do not know which one. You know the weight of a genuine half-dollar in grams and you know that each fake one weighs one gram more than it should. You may weigh the coins on a scale that reads in grams. What is the smallest number of weighings required to identify the counterfeit stack?
Puzzle #8
A young man lives in Manhattan near a subway express station. He has two girlfriends, one in Brooklyn and one in The Bronx. To visit the girl in Brooklyn he takes a train on the downtown side of the platform; to visit the girl in The Bronx he takes a t rain on the uptown side of the same platform. Since he likes both girls equally well, he simply takes the first train that comes along. In this way he lets chance determine which girl he visits. He reaches the subway platform at a random time each Satu rday afternoon. Brooklyn and Bronx trains arrive at the station equally often - every ten minutes. Yet for some obscure reason he finds himself going to Brooklyn nine times out of ten. Can you think of a good reason why the odds so heavily favor Brookl yn?
Puzzle #9
Needing to find a successor, and having four equally intelligent and capable advisors to choose from, the leader of a mythical country devised a test to pick the best one: the four were tightly blindfolded and seated around a table. The leader then said , "I will now place either a blue mark or a red mark on each of your foreheads. You will then remove your blindfolds, and each of you who sees more blue marks than red marks on your companions will stand up. The first person who can correctly name his o wn color and the reason will be the next leader." The leader then placed the marks, the blindfolds were removed, the candidates looked around, and all four stood up. For several minutes, each stood silent, thinking. Finally, one of them spoke: "I have a blue mark." He then successfully explained how he had figured it out. How were the candidates marked, and how did one of them determine the color of his mark?
Puzzle #10
A logician vacationing in the South Seas finds herself on an island inhabited by two groups of people. Members of one group always tell the truth and members of the other group always lie. She comes to a fork in the road knowing that one of the forks le ads to town and the other into the wilderness. There is a man standing by the fork who belongs to one of the two groups on the island, but the logician can't tell by looking at him to which group he belongs. The logician thinks for a moment, then asks o ne question only. From the reply she knows which road to take. What question does she ask?
Puzzle #11
On last New Year's Day a mathematician was puzzled by the strange way in which his small daughter began to count on the fingers of her left hand. She started by calling the thumb 1, the index finger 2, the middle finger 3, the ring finger 4, the little f inger 5, then she reversed direction, calling the ring finger 6, middle finger 7, first finger 8, thumb 9, then back to the index finger for 10, middle finger for 11, and so on. She continued to count back and forth in this peculiar manner until she reac hed a count of 20 on her ring finger. "What in the world are you doing?" her father asked. The girl stamped her foot. "Now you've made me forget where I was. I'll have to start all over again. I'm counting up to 1995 to see what finger I'll end on." The mathematician closed his eyes and made a simple mental calculation. "You'll end on your _______," he said. When the girl finished her count and found that her father was right, she was so impressed by the predictive power of mathematics that she decided to work twice as hard on her arithmetic lessons. How did the father arrive at his prediction and what finge r did he predict?
Puzzle #12
A pirate ship capable of 20 knots is sitting motionless on an infinite sea in the fog. Another ship carrying tons of gold and a weak unarmed crew is sitting exactly 10 nautical miles away on one of the 360 degree radials corresponding to the degrees on a compass. It is capable of only 10 knots and immediately sets out to escape by setting a course directly away from the pirate ship at top speed. The pirate ship knows what's happening, but can't see the other ship (knowing how far away it is when it sta rts running, but not where). Is there a course the pirate ship can sail that will guarantee interception of the gold ship? They must be close enough to touch because of the fog. If so, describe the course/strategy.
Puzzle #13
Variation on #12: A pirate ship capable of 20 knots is sitting motionless on an infinite sea in the fog. Another ship carrying tons of gold and a weak unarmed crew is sitting exactly 10 nautical miles away on one of the 360 deg ree radials corresponding to the degrees on a compass. It is capable of only 10 knots and immediately sets out to escape by setting a course directly away from the pirate ship at a random speed (the gold ship may speed up or slow down or even stop, but i t cannot deviate from it's course). The pirate ship knows what's happening, but can't see the other ship (knowing how far away it is when it starts running, but not where). Is there a course the pirate ship can sail that will guarantee interception of t he gold ship? They must be close enough to touch because of the fog. If so, describe the course/strategy.
Puzzle #14
Find the digits that the various letters in the following represent to make the calculations correct:
NINE - TEN = TWO; NINE - ONE = ALL.
(Each letter represents a unique single digit)
Puzzle #15
A particular phonograph record (remember those?) measures exactly 12 inches in diameter. The center of it that contains the hole and the label is 2.5 inches in diameter. Assuming the remainder of the record is grooved uniformly and there are exactly 29 grooves per centimeter measuring radially, how many total grooves are there on the record?
Puzzle #16
If a hole is drilled through the center of a sphere such that the height of the resulting cylindrically shaped hole is exactly 6 inches, what is the remaining volume of the sphere?
Three identical boxes, one containing two black marbles, one containing a black marble and a white marble, and a third containing two white marbles, are placed side by side on a table. Originally each box had a label on it describing its contents, but so meone has mixed up the labels so that each one is incorrect (i.e., no label is correct). The problem is to determine the contents of each box by a sampling process: choosing one box, blindly removing one marble from it, and repeating the process as m any times as it takes to positively infer the contents of each box. What sampling procedure would you use to identify the contents of each box with the fewest number of draws?
Puzzle #2
A commuter is in the habit of arriving at his suburban station each evening at exactly five o'clock. His chauffeur always meets the train and drives him home. One day he takes an earlier train, arriving at the station at four. The weather is pleasant, so instead of telephoning home he starts walking along the route always taken by his driver. They meet somewhere along the way. He gets into the car and they drive home, arriving at the house ten minutes earlier than usual. Assuming that the chauffeur always drives at a constant speed, and had left just in time to meet the five o'clock train, can you determine how long the commuter walked before he was picked up?
Puzzle #3
The following conversation took place in a home supply/hardware type store like Lowe's or National Home Center:
"How much will one cost?"
"Seventy five cents," replied the clerk.
"And how much will twelve cost?"
"A dollar fifty."
"Okay, I'll take nine hundred and twelve."
"That will be two dollars and twenty five cents."
What was the customer buying?
Puzzle #4
An explorer walks one mile due south, turns and walks one mile due east, then walks one mile due north and finds himself back where he started. He then shoots a bear. What color is the bear? The age-old answer is white because he must have started at t he North Pole. Is there anywhere else on earth where one could walk a mile south, a mile east, and a mile north and be back at the exact same spot? Explain.
Puzzle #5
A carpenter, working with a power saw, wishes to cut a wooden cube, three inches on a side, into 27 one-inch cubes. He can easily do this by making six cuts through the cube, keeping the pieces together in the cube shape. Can he reduce the number of nec essary cuts by rearranging the pieces after each cut? Explain.
Puzzle #6
A cylindrical hole exactly 6 inches long has been drilled straight through the center of a solid sphere. What is the volume remaining in the sphere?
Puzzle #7
You have ten stacks of coins, each consisting of ten half-dollars. One entire stack is counterfeit, but you do not know which one. You know the weight of a genuine half-dollar in grams and you know that each fake one weighs one gram more than it should. You may weigh the coins on a scale that reads in grams. What is the smallest number of weighings required to identify the counterfeit stack?
Puzzle #8
A young man lives in Manhattan near a subway express station. He has two girlfriends, one in Brooklyn and one in The Bronx. To visit the girl in Brooklyn he takes a train on the downtown side of the platform; to visit the girl in The Bronx he takes a t rain on the uptown side of the same platform. Since he likes both girls equally well, he simply takes the first train that comes along. In this way he lets chance determine which girl he visits. He reaches the subway platform at a random time each Satu rday afternoon. Brooklyn and Bronx trains arrive at the station equally often - every ten minutes. Yet for some obscure reason he finds himself going to Brooklyn nine times out of ten. Can you think of a good reason why the odds so heavily favor Brookl yn?
Puzzle #9
Needing to find a successor, and having four equally intelligent and capable advisors to choose from, the leader of a mythical country devised a test to pick the best one: the four were tightly blindfolded and seated around a table. The leader then said , "I will now place either a blue mark or a red mark on each of your foreheads. You will then remove your blindfolds, and each of you who sees more blue marks than red marks on your companions will stand up. The first person who can correctly name his o wn color and the reason will be the next leader." The leader then placed the marks, the blindfolds were removed, the candidates looked around, and all four stood up. For several minutes, each stood silent, thinking. Finally, one of them spoke: "I have a blue mark." He then successfully explained how he had figured it out. How were the candidates marked, and how did one of them determine the color of his mark?
Puzzle #10
A logician vacationing in the South Seas finds herself on an island inhabited by two groups of people. Members of one group always tell the truth and members of the other group always lie. She comes to a fork in the road knowing that one of the forks le ads to town and the other into the wilderness. There is a man standing by the fork who belongs to one of the two groups on the island, but the logician can't tell by looking at him to which group he belongs. The logician thinks for a moment, then asks o ne question only. From the reply she knows which road to take. What question does she ask?
Puzzle #11
On last New Year's Day a mathematician was puzzled by the strange way in which his small daughter began to count on the fingers of her left hand. She started by calling the thumb 1, the index finger 2, the middle finger 3, the ring finger 4, the little f inger 5, then she reversed direction, calling the ring finger 6, middle finger 7, first finger 8, thumb 9, then back to the index finger for 10, middle finger for 11, and so on. She continued to count back and forth in this peculiar manner until she reac hed a count of 20 on her ring finger. "What in the world are you doing?" her father asked. The girl stamped her foot. "Now you've made me forget where I was. I'll have to start all over again. I'm counting up to 1995 to see what finger I'll end on." The mathematician closed his eyes and made a simple mental calculation. "You'll end on your _______," he said. When the girl finished her count and found that her father was right, she was so impressed by the predictive power of mathematics that she decided to work twice as hard on her arithmetic lessons. How did the father arrive at his prediction and what finge r did he predict?
Puzzle #12
A pirate ship capable of 20 knots is sitting motionless on an infinite sea in the fog. Another ship carrying tons of gold and a weak unarmed crew is sitting exactly 10 nautical miles away on one of the 360 degree radials corresponding to the degrees on a compass. It is capable of only 10 knots and immediately sets out to escape by setting a course directly away from the pirate ship at top speed. The pirate ship knows what's happening, but can't see the other ship (knowing how far away it is when it sta rts running, but not where). Is there a course the pirate ship can sail that will guarantee interception of the gold ship? They must be close enough to touch because of the fog. If so, describe the course/strategy.
Puzzle #13
Variation on #12: A pirate ship capable of 20 knots is sitting motionless on an infinite sea in the fog. Another ship carrying tons of gold and a weak unarmed crew is sitting exactly 10 nautical miles away on one of the 360 deg ree radials corresponding to the degrees on a compass. It is capable of only 10 knots and immediately sets out to escape by setting a course directly away from the pirate ship at a random speed (the gold ship may speed up or slow down or even stop, but i t cannot deviate from it's course). The pirate ship knows what's happening, but can't see the other ship (knowing how far away it is when it starts running, but not where). Is there a course the pirate ship can sail that will guarantee interception of t he gold ship? They must be close enough to touch because of the fog. If so, describe the course/strategy.
Puzzle #14
Find the digits that the various letters in the following represent to make the calculations correct:
NINE - TEN = TWO; NINE - ONE = ALL.
(Each letter represents a unique single digit)
Puzzle #15
A particular phonograph record (remember those?) measures exactly 12 inches in diameter. The center of it that contains the hole and the label is 2.5 inches in diameter. Assuming the remainder of the record is grooved uniformly and there are exactly 29 grooves per centimeter measuring radially, how many total grooves are there on the record?
Puzzle #16
If a hole is drilled through the center of a sphere such that the height of the resulting cylindrically shaped hole is exactly 6 inches, what is the remaining volume of the sphere?
Unix/Linx bootupand login
-------------------------
Process 0 - swapper
Process 1 - init
getty - monitors terminal line
user login procedure
getty execs a login shell for the user
-------------------------
Process 0 - swapper
Process 1 - init
getty - monitors terminal line
user login procedure
getty execs a login shell for the user
-------------------------
GNU Linux pthreads
pthread_t (object)
pthread_attr_t (object) --- pthread_attr_init,pthread_attr_destroy
Thread’s detach state.A thread may be created as a joinable
thread (the default) or as a detached thread.
pthread_attr_setdetachstate
pthread_detach
Even if a thread is created in a joinable state, it may later be
turned into a detached thread.To do this, call pthread_detach.
Once a thread is detached, it cannot be made joinable again.
pthread_create
pthread_self
pthread_equal
pthread_exit
pthread_cancel --> PTHREAD_CANCELED
A canceled thread may later be joined; in fact, you should join
a canceled thread to free up its resources, unless the thread is
detached
asynchronously cancelable.
synchronously cancelable - cancellation points.The thread will
queue a cancellation request until it
reaches the next cancellation point.
uncancelable
pthread_setcanceltype
PTHREAD_CANCEL_ASYNCHRONOUS OR PTHREAD_CANCEL_DEFERRED
pthread_testcancel - direct way to create a cancellation point
- process a pending cancellation in a
synchronously cancelable thread.
pthread_key_t(object) --- pthread_key_create,pthread_setspecific,pthread_getspecific
thread-specific data area.
pthread_join
pthread_attr_t (object) --- pthread_attr_init,pthread_attr_destroy
Thread’s detach state.A thread may be created as a joinable
thread (the default) or as a detached thread.
pthread_attr_setdetachstate
pthread_detach
Even if a thread is created in a joinable state, it may later be
turned into a detached thread.To do this, call pthread_detach.
Once a thread is detached, it cannot be made joinable again.
pthread_create
pthread_self
pthread_equal
pthread_exit
pthread_cancel --> PTHREAD_CANCELED
A canceled thread may later be joined; in fact, you should join
a canceled thread to free up its resources, unless the thread is
detached
asynchronously cancelable.
synchronously cancelable - cancellation points.The thread will
queue a cancellation request until it
reaches the next cancellation point.
uncancelable
pthread_setcanceltype
PTHREAD_CANCEL_ASYNCHRONOUS OR PTHREAD_CANCEL_DEFERRED
pthread_testcancel - direct way to create a cancellation point
- process a pending cancellation in a
synchronously cancelable thread.
pthread_key_t(object) --- pthread_key_create,pthread_setspecific,pthread_getspecific
thread-specific data area.
pthread_join
How many processes will be created-- fork?
sandesh@nextfour:~/labs> cat fork.c
#include
#include
#include
int count;
main()
{
int i;
for(i=0;i<3;i++)
fork();
count++;
printf("Hello %d\n",count);
}
sandesh@nextfour:~/labs> gcc fork.c
sandesh@nextfour:~/labs> ./a.out
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
sandesh@nextfour:~/labs>
#include
#include
#include
int count;
main()
{
int i;
for(i=0;i<3;i++)
fork();
count++;
printf("Hello %d\n",count);
}
sandesh@nextfour:~/labs> gcc fork.c
sandesh@nextfour:~/labs> ./a.out
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
Hello 1
sandesh@nextfour:~/labs>
Linux time keeping - Timer interrupt, jiffies, xtime
Under Linux system time is measured in "ticks" since the system was stated up. One tick represents 10 milliseconds, so the timer interrupt is triggered 100 times per second. The timer ticks are stored in the variable -
unsigned long volatile jiffies
jiffies
~~~~~~~
Every time a timer interrupt occurs, the value of the variable is
increamented. jiffies is initialised to 0 when the system boots, and
is thus the number of clock ticks since the computer was tured on.
unsigned long volatile jiffies
jiffies
~~~~~~~
Every time a timer interrupt occurs, the value of the variable is
increamented. jiffies is initialised to 0 when the system boots, and
is thus the number of clock ticks since the computer was tured on.
Segmentation Fault and Bus Error
Segmentation Fault
Wikipedia Page : http://en.wikipedia.org/wiki/Segmentation_fault
A segmentation fault occurs when your program tries to access memory locations that haven't been allocated for the program's use. Here are some common errors that will cause this problem:
scanf("%d", number);
In this case, number is integer. scanf() expects you to pass it the address of the variable you want to read an integer into. But, the writer has fogotten to use the `&' before number to give scanf the address of the variable. If the value of number happened to be 3, scanf() would try to access memory location 3, which is not accessible by normal users. The correct way to access the address of number would be to place a `&' (ampersand) before number:
scanf("%d", &number);
Another common segmentation fault occurs when you try to access an array index which is out of range. Let's say you set up an array of integers:
int integers[80];
If, in your program, you try to use an index (the number within the brackets) over 79, you will ``step out of your memory bounds'', which causes a segmentation fault. To correct this, rethink your array bounds or the code that is using the array.
Bus Error
Wikipedia Page : http://en.wikipedia.org/wiki/Bus_error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A SIGBUS is often caused by accessing data at an address that is not aligned to
a multiple of the width of the data. A 4 byte int must be aligned on a multiple
of 4. An 8 byte long must be aligned on a multiple of 8.
(processor) bus error - A fatal failure in the execution of a machine language
instruction resulting from the processor detecting an anomalous condition on its
bus. Such conditions include invalid address alignment (accessing a multi-byte
number at an odd address), accessing a physical address that does not correspond
to any device, or some other device-specific hardware error. A bus error
triggers a processor-level exception which Unix translates into a "SIGBUS"
signal which, if not caught, will terminate the current process.
From Cisco documentation
The system encounters a bus error when the processor tries to access a memory
location that either does not exist (a software error) or does not respond
properly (a hardware problem).
What is the difference between a Bus Error and a Segmentation Error?
Full Article:
Both are addressing errors, such as trying to address memory outside of your
legal address space. A segmentation error is detected by the kernel, while a
bus error is detected by the hardware.
These errors will occur when the program tries to access a memory location
outside its address space. That is, accessing uninitilized pointers, or even
mangled pointers (ones which have no reference or have been deleted).
The Bus error means that the kernel did not detecet the problem on its own;
the memory system realized the error.
Wikipedia Page : http://en.wikipedia.org/wiki/Segmentation_fault
A segmentation fault occurs when your program tries to access memory locations that haven't been allocated for the program's use. Here are some common errors that will cause this problem:
scanf("%d", number);
In this case, number is integer. scanf() expects you to pass it the address of the variable you want to read an integer into. But, the writer has fogotten to use the `&' before number to give scanf the address of the variable. If the value of number happened to be 3, scanf() would try to access memory location 3, which is not accessible by normal users. The correct way to access the address of number would be to place a `&' (ampersand) before number:
scanf("%d", &number);
Another common segmentation fault occurs when you try to access an array index which is out of range. Let's say you set up an array of integers:
int integers[80];
If, in your program, you try to use an index (the number within the brackets) over 79, you will ``step out of your memory bounds'', which causes a segmentation fault. To correct this, rethink your array bounds or the code that is using the array.
Bus Error
Wikipedia Page : http://en.wikipedia.org/wiki/Bus_error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A SIGBUS is often caused by accessing data at an address that is not aligned to
a multiple of the width of the data. A 4 byte int must be aligned on a multiple
of 4. An 8 byte long must be aligned on a multiple of 8.
(processor) bus error - A fatal failure in the execution of a machine language
instruction resulting from the processor detecting an anomalous condition on its
bus. Such conditions include invalid address alignment (accessing a multi-byte
number at an odd address), accessing a physical address that does not correspond
to any device, or some other device-specific hardware error. A bus error
triggers a processor-level exception which Unix translates into a "SIGBUS"
signal which, if not caught, will terminate the current process.
From Cisco documentation
The system encounters a bus error when the processor tries to access a memory
location that either does not exist (a software error) or does not respond
properly (a hardware problem).
What is the difference between a Bus Error and a Segmentation Error?
Full Article:
Both are addressing errors, such as trying to address memory outside of your
legal address space. A segmentation error is detected by the kernel, while a
bus error is detected by the hardware.
These errors will occur when the program tries to access a memory location
outside its address space. That is, accessing uninitilized pointers, or even
mangled pointers (ones which have no reference or have been deleted).
The Bus error means that the kernel did not detecet the problem on its own;
the memory system realized the error.
Semaphore, Mutex, Conditional variable, Spin lock
Difference between mutex and semaphore
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A mutex has two possible states: unlocked (not owned by any thread), and locked (owned by one thread). A mutex can never be owned by two different threads simultaneously. A thread attempting to lock a mutex that is already locked by another thread is suspended until the owning thread unlocks the mutex first.
Example -
A shared global variable x can be protected by a mutex as follows:
int x;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
All accesses and modifications to x should be bracketed by calls to pthread_mutex_lock and pthread_mutex_unlock as follows:
pthread_mutex_lock(&mut);
/* operate on x */
pthread_mutex_unlock(&mut);
TBD
Is it possible to implement semaphores without special machine instructions(compare and swap instruction(IBM 370) or atomic read
and clear instruction(AT &T 3B20))?
YES - Bach Chapter 12 Multiprocessor Systems
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A mutex has two possible states: unlocked (not owned by any thread), and locked (owned by one thread). A mutex can never be owned by two different threads simultaneously. A thread attempting to lock a mutex that is already locked by another thread is suspended until the owning thread unlocks the mutex first.
Example -
A shared global variable x can be protected by a mutex as follows:
int x;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
All accesses and modifications to x should be bracketed by calls to pthread_mutex_lock and pthread_mutex_unlock as follows:
pthread_mutex_lock(&mut);
/* operate on x */
pthread_mutex_unlock(&mut);
TBD
Is it possible to implement semaphores without special machine instructions(compare and swap instruction(IBM 370) or atomic read
and clear instruction(AT &T 3B20))?
YES - Bach Chapter 12 Multiprocessor Systems
Big Endian versus Little Endian
Big-endian means that the most significant byte is stored at the lowest memory address
0x12345678
(low address--->high address)
Read Wikipedia Page: http://en.wikipedia.org/wiki/Endianness
C program to find out whether a machine is big endian or little endian
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is endian-ness bit level /byte-level/word-level?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On a byte addressed machine it is byte level.
Examples of CPU Architectures
~~~~~~~~~~~~~~~~~~~~~~~
x86 processors use the little-endian format (sometimes called the Intel format).
Motorola processors have generally used big-endian. PowerPC (which includes Apple's Macintosh line prior to the Intel switch) and System/370 also adopt big-endian. SPARC historically used big-endian, though version 9 is bi-endian
Why different processor architectures choose different endian-ness? Is there any advantage of one over other?
0x12345678
(low address--->high address)
Read Wikipedia Page: http://en.wikipedia.org/wiki/Endianness
C program to find out whether a machine is big endian or little endian
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include
main () {
int i = 0x12345678;
if (*(char *)&i == 0x12)
printf ("Big endian\n");
else if (*(char *)&i == 0x78)
printf ("Little endian\n");
}
Is endian-ness bit level /byte-level/word-level?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On a byte addressed machine it is byte level.
Examples of CPU Architectures
~~~~~~~~~~~~~~~~~~~~~~~
x86 processors use the little-endian format (sometimes called the Intel format).
Motorola processors have generally used big-endian. PowerPC (which includes Apple's Macintosh line prior to the Intel switch) and System/370 also adopt big-endian. SPARC historically used big-endian, though version 9 is bi-endian
Why different processor architectures choose different endian-ness? Is there any advantage of one over other?
Salient points about Unix/Linux
- Time sharing system
- Each user file is simply a sequence of bytes.
- Disk files and I/O devices are treated as similarly as possible.
- CPU scheduling is simple priority algorithm.
- For unix development intent was to have the kernel and libraries provide a small set of facilities that was sufficiently powerful to allow a person to build a more complex system if one were needed.
- -----------
- The kernel is not a separate set of processes that run in parallel to user processes, but is part of each user process.
- The kernel permanently resides in main memory as does the currently executing process (or part of it at least).
- Interrupt handler runs in the context of currently running process.
- All system calls return -1 on failure.
- When a process executes a system call, the execution mode of the process changes from user mode to kernel mode.
- .
- Every process except process 0 is created when another process executes the fork system call. Process 0 is a special process that is created bby hand when the system boots. After forking a child process (Process 1), process 0 becomes a swapper process. Process 1, known as init, is the ancestor of every other process.
- .
- .
- -----------------
- Kernel cannot preempt a process and switch context to another process while executing in kernel mode
- Kernel masks out interrupts when executing a critical region of code if an interrupt handler could corrupt kernel data structures.
- ..
Linux Terms/Concepts
Bottom Halves
Exceptions, traps, interrupts and signals
Exceptions
- Unexpected events causes by a process (internal source) such as addressing illegal memory, executing privileged instructions, dividing by zero
- Synchronous
- Exceptions happen in the middle of the execution of an instruction, and the system attempts to restart the instruction after handling the exception.
Interrupts
- Interrupts the CPU asynchronously
- I/O peripherals and system clock (from external sources) generated interrupts.
- Interrupts are considered to happen between the execution of two instructions, and the system continues with the next instruction after servicing the interrupt.
Signals
SIGINT - Stop Command before completion
SIGQUIT - Stops the currently executing program and dumps its current memory image to file name core in the current directory
SIGILL - Produced by illegal instruction
SIGSEGV - Attempt to address memory outside of the legal virtual memory space of process.
SIGKILL - Kill Signal (kill -9)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17. Interrupts and Exceptions
"(with interrupts) the processor doesn't waste its time looking for
work - when there is something to be done, the work comes looking
for the processor."
- Peter Norton
INTERRUPTS AND EXCEPTIONS
Interrupts and exceptions both alter the program flow. The difference
between the two is that interrupts are used to handle external events
(serial ports, keyboard) and exceptions are used to handle instruction
faults, (division by zero, undefined opcode).
Interrupts are handled by the processor after finishing the current
instruction. If it finds a signal on its interrupt pin, it will look up
the address of the interrupt handler in the interrupt table and pass
that routine control. After returning from the interrupt handler
routine, it will resume program execution at the instruction after the
interrupted instruction.
Exceptions on the other hand are divided into three kinds. These are
Faults, Traps and Aborts. Faults are detected and serviced by the
processor before the faulting instructions. Traps are serviced after
the instruction causing the trap. User defined interrupts go into this
category and can be said to be traps; this includes the MS-DOS INT 21h
software interrupt, for example. Aborts are used only to signal severe
system problems, when operation is no longer possible.
See the below table for information on interrupt assignments in the
Intel 386, 486 SX/DX processors, and the Pentium processor. Type
specifies the type of exception.
------------------------------
Vector number Description
------------------------------
0 Divide Error (Division by zero)
1 Debug Interrupt (Single step)
2 NMI Interrupt
3 Breakpoint
4 Interrupt on overflow
5 BOUND range exceeded
6 Invalid Opcode
7 Device not available (1)
8 Double fault
9 Not used in DX models and Pentium (2)
10 Invalid TSS
11 Segment not present
12 Stack exception
13 General protection fault
14 Page fault
15 Reserved
16 Floating point exception (3)
17 Alignment check (4)
18 – 31 Reserved on 3/486, See (5) for Pentium
32 – 255 Maskable, user defined interrupts
------------------------------
(1) Exception 7 is used to signal that a floating point processor is
not present in the SX model. Exception 7 is used for programs
and OSs that have floating point emulation. In addition, the DX
chips can be set to trap floating point instructions by setting
bit 2 of CR0.
(2) Exception 9 is Reserved in the DX models and the Pentium, and is
only used in the 3/486 SX models to signal Coprocessor segment
overrun. This will cause an Abort type exception on the SX.
(3) In the SX models this exception is called 'Coprocessor error'.
(4) Alignment check is only defined in 486 and Pentiums. Reserved
on any other Intel processor.
(5) For Pentiums Exception 18 is used to signal what is called an
'Machine check exception'.
The other interrupts, (32-255) are user defined. They differ in use
from one OS to another.
For a list of MS-DOS interrupts, see 'Obtaining HELPPC' (Subject #6) or
Ralf Browns Interrupt List (Subject #11)
Contributor: Patrik Ohman, patrik@astrakan.hgs.se
Last changed: 10 Jan 95
CPU Scheduling -- Different types of CPU scheduling algorithms
Scheduling Criteria -
CPU Utilization:
Throughput: Measure of work done. Number of processes that are completed pe time unit.
Turnaround time: The interval from the time of submission of a process to the time of completion. Turnaround time is sum of the periods spent waiting to get into memory, waiting in the ready queue, executing on the CPU and doing I/O.
Waiting time: Waiting time is the sum of the periods spend waiting in the ready queue.
Response time: Time from submission of a request until the first response is produced. Good measure for interactive systems.
Scheduling Algorithms:
FCFS (First-Come First Served)
Shortest Job First
Priority Scheduling
Round-Robin Scheduling
Multilevel Queue Scheling
Multilevel Feedback Queue Scheduling
Real Time Scheduling -
Hard Real Time Systems
Soft Real Time System
Priority Inversion
Priority-Inheritance Protocol
CPU Utilization:
Throughput: Measure of work done. Number of processes that are completed pe time unit.
Turnaround time: The interval from the time of submission of a process to the time of completion. Turnaround time is sum of the periods spent waiting to get into memory, waiting in the ready queue, executing on the CPU and doing I/O.
Waiting time: Waiting time is the sum of the periods spend waiting in the ready queue.
Response time: Time from submission of a request until the first response is produced. Good measure for interactive systems.
Scheduling Algorithms:
FCFS (First-Come First Served)
Shortest Job First
Priority Scheduling
Round-Robin Scheduling
Multilevel Queue Scheling
Multilevel Feedback Queue Scheduling
Real Time Scheduling -
Hard Real Time Systems
Soft Real Time System
Priority Inversion
Priority-Inheritance Protocol
fork, vfork, copy-on-write and clone
From man page of fork in linux
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fork creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.
Under Linux, fork is implemented using copy-on-write pages, so the only penalty incurred by fork is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
RETURN VALUE
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution.
On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
ERRORS
EAGAIN fork cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child.
ENOMEM fork failed to allocate the necessary kernel structures because memory is tight.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fork creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.
Under Linux, fork is implemented using copy-on-write pages, so the only penalty incurred by fork is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
RETURN VALUE
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution.
On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
ERRORS
EAGAIN fork cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child.
ENOMEM fork failed to allocate the necessary kernel structures because memory is tight.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inter-process communication
Signals -

Power point slide of this picture: pipe.ppt
FIFOs (Named pipes) - created by open() or mknod
File locking
System V IPC (which works on most unix flavours)
Spin Locks
Read Write Locks
Memory Mapped Files
Unix Sockets
- Signals inform processes of the occurrences of asynchcronous events.
- Process may send each other signal with the kill system call, or the kernel may send signals internally.
- 19 Signals are there in system V
- Only related processes, descendents ofa process that issued the pipe call, can share access to unnamed pipes.
Power point slide of this picture: pipe.ppt
FIFOs (Named pipes) - created by open() or mknod
- All processes can access a named pipe regardless of their relationship.
File locking
System V IPC (which works on most unix flavours)
- Message Queues:
- Semaphores:
- Shared Memory: Process share parts of their virtual address space. Processes read and write shared memory using the same machine instructions they use to read write regular memory. After attaching shared memory, it becomes part of the virtual address space of process, accessible in the same way other virtual addresses are.
Spin Locks
Read Write Locks
Memory Mapped Files
Unix Sockets
Subscribe to:
Posts (Atom)