OS Test 1 Q/A
Determine the output for these commands: variable="Dennis" echo '$variable'
$variable
Give two reasons why we should not give the users the power todisable/enable interrupts in a multiprogrammed computer system.
(i) they may (unintentionally) forget to enable them which means all (hardware & software) interrupts will be ignored. (ii) they may intentionally abuse this power and let their processes dominate the system resources.
What is an atomic operation?
An operation that can not have it's execution suspended until it is fully completed. Generally, it is a single operation that can not be interrupted or divided into smaller operations.
Can you suggest a strategy that can achieve the desired result in the previous question, i.e. no circular wait can occur in the system
Assign a number to each resource and require that, at any moment, a process can only request a resource whose number is higher than that of any resource it is currently holding.
Explain why the primary purpose of having an O.S. changed from the 1960 to the 1990s.
In the past, the efficiency is the most important goal because the computer is much more expensive. The operating systems concentrated on the optimum use of computer resources. The systems such as batch processing, spooling, multiprogramming, and time sharing are developed to reduce the cpu idle time which is wasted. In 1990s, as the cost of hardware decreased, it was feasible to have a computer dedicated to a single user. The cpu utilization is not a primary concern. The user's convenience has become more important. OS such as UNIX/Linux, Windows, and Apple Macintosh have been developed.
What does it mean to say "rand() call is not MT-safe"?
MT-Safe : MultiThread-SafeThis means that the behavior of the function rand() is not stable when twothreads try to use it at the same time. To get around this problem, we useMT-safe interfaces (such as rand_r()). However, rand_r() doesn't existon some multithreaded operating systems (e.g. LINUX), therefore, youneed to execute such calls inside a Critical Section to make sure thatonly one thread can call the function at any one time. Example: pthead_mutex_t rand_mutex; pthread_mutex_lock( &rand_mutex ); int a = rand() % 5; pthread_mutex_unlock( &rand_mutex );
Many modern O.S.s use a microkernel design. What does that mean?
Microkernel is a small privileged OS core that provides process scheduling, memory management, and communication services and relies on other processes to perform some of the functions traditionally associated with the operating system kernel.It removes all nonessential components from the kernel, and implementsthem as system and user-level programs. The result is a smaller kernel.Amoeba, Chorus, Mach, and Windows/NT use microkernel design approach.
Draw a simple Unix 'Process State' graph.
NEW --create--> READY ---cpu avail---> RUNNING ---exit system--> TERMINATED process ^<--time expires-----/ \ / \ event event wait completed / \ / \ v BLOCKED/WAITING
You will be given a 'claim matrix', an 'allocation matrix' and a 'resource vector' for a set of processes. Is this a safe state? Claim Matrix R1 R2 R3 P1 3 2 2 P2 6 1 3 P3 3 1 4 P4 4 2 2 Allocation Matrix R1 R2 R3 P1 1 0 0 P2 5 1 1 P3 2 1 1 P4 0 0 2 Resource Vector R1 R2 R3 9 3 6
Need Matrix R1 R2 R3 P1 2 2 2 P2 1 0 2 P3 1 0 3 P4 4 2 0 Available Vector R1 R2 R3 1 1 2 Yes, this is a safe state. Processes can run to completion in this order: <P2, P1, P3, P4>
You will then be given a resource request for one of the processes. For example, if Process P3 requests 1 unit of R3, should we grant this request? If yes, give a <sequence> in which all processes can run to completion.
No, we should not grant this request; because, if we do, the system goes into an UNSAFE STATE. If we grant P3's request then the Need Matrix and available vector become: Need Matrix R1 R2 R3 P1 2 2 2 P2 1 0 2 P3 1 0 2 P4 4 2 0 Available Vector R1 R2 R3 1 1 1No process is guaranteed to finish. Therefore, the system runs into anUNSAFE STATE and there is potential for deadlock.Resource Manager should not grant P3's request!
Can you build a system where mutual exclusion condition is eliminated?
No. It is a resource constraint and most resources (if not all) require it.
What is a monolithic kernel?
Old OSs had Monolithic kernels which are large kernels containingvirtually the complete operating system, including scheduling, filesystem, device drivers, and memory management. All the functionalcomponents of the kernel have access to all of its internal datastructures and routines. Typically, a monolithic kernel isimplemented as a single process, with all elements sharing the sameaddress space. Examples of such systems are: UNIX, MS-DOS, VMS,OS/360, and MULTICS.
What is a context switch?
Switching the CPU to another process.
Could you suggest a solution which is both correct and fair?
Yes. Introduce a new semaphore called "writePending" which is shared by both readers and writers. It will force the blocked readers and writers to enter a waiting queue in the order that they have arrived. The associated P and V calls are added to the original code as follows:int readCount=0, writeCount=0;semaphore mutex1=1, mutex2=1;semaphore readBlock=1, writeBlock=1;semaphore writePending=1;reader() { while(TRUE) { <other computing>; P(writePending); P(readBlock); P(mutex1); ....... V(mutex1); V(readBlock); V(writePending); access(resource); ......... }}writer() { while(TRUE) { <other computing>; P(writePending); P(mutex2); ........ V(mutex2); P(writeBlock); access(resource); V(writeBlock); V(writePending); ........... }}
Give an example of something that a process might do to initiate a voluntary context switch. Relate this answer to the Process State graph.
When a process initiates an I/O Read/Write or event wait(). In the Process State graph, the transition is from Running State to BLOCKED(Waiting) State.
What is a spinlock?
When a process is in its critical section, any other process that tries to enter the same CS must loop continuously in the entry code of the CS until the first one gets out. The spinlock is the most common technique used for protecting a CS in Linux. It is easy to implement but has the disadvantage that locked-out threads continue to execute in a busy-waiting mode. Thus spinlocks are most effective in situations where the wait-time is expected to be very short. spin_lock(&lock) /* Critical Section */ spin_unlock(&lock)
Give an example of something that would cause a process to experience an involuntary context switch. Relate this answer to the Process State graph.
When a process is interrupted by an exernal source such as a timer. In the Process State graph, the transition is from Running to Ready State.
What are the necessary conditions for a deadlock to exist.
a) mutual exclusion; b) hold and wait; c) no preemption d) circular wait.
How can the code segment "if( i < y ) cout << foobar(i,y);" be made to behave as if it were atomic? Answer the question by recoding the segment.
pthread_mutex_t m=1; pthread_mutex_lock( &m ); if( i < y ) cout << foobar( i, y ); pthread_mutex_unlock( &m );
What would you expect to see (what instructions) surrounding the 'critical section' code?
pthread_mutex_t mp; pthread_mutex_lock( &mp ); <CRITICAL SECTION> pthread_mutex_unlock( &mp );
What is the effect of executing pthread_yield()?
pthread_yield(): stop executing the caller thread and yield the CPU to another thread
Write a command which reads from the keyboard and stores it in the variable kbinput
read kbinput
Write a shell statement which first adds the numbers 5 and 7 and stores the result in $sum
sum=$(echo '5 + 7' | bc)
True False ? UNIX kernel is designed as a microkernel
FALSE. UNIX is a monolithic kernel, meaning that the process,memory, device, and file managers are all implemented in a singlesoftware module.
Name at least two important differences between a POSIX thread created through a pthread_create() call and a child process created through a fork() call.
1) Threads share data space and file descriptors with the other threads and the parent process while forked process doesn't 2) a forked process has a seperate and unique PID and hence a process control block (PCB) while the threads created by a process uses their parent's PCB. 3) it takes less time to create a new thread, less time to switch between two threads within the same process, less time to terminate a thread 4) Thread Library provides more control over the execution of concurrent threads through system calls such as pthread_yield(), pthread_suspend(), pthread_kill(), and pthread_continue()
Explain under what circumstances a spinlock might be more efficient than the alternative.
1. If you have more processor power than you need (e.g. in multiprocessor systems). Spinlock do not require context switch when a process must wait on a lock, and therefore it is more efficient.2. when the locks are expected to be held for a short time, a spinlock might be more efficient (saves the context switch time, therefore, preferred).
Assume that you have globally defined struct Shared { char Name[10]; int Value; } S1, S2; thread_t tid; void * RtnValue; void * FooBar(void * arg); // For this problem, arg will point to aninstance of struct SharedShow the correct way to: 1. Store "THREAD 1" in S1's Name field: o ___________________________________________ 2. Pass S1 in the following call: o pthread_create(&tid,NULL,FooBar,_____________________); 3. From within the function FooBar, print the Name that was passed inside the struct: o printf("The Name Received = %s\n", _____________________________________________; 4. store 2 times the thread id into the Value field of arg: o ______________________ = __________________________ 5. return the struct via a thr_exit: o pthread_exit( ______________________________ ); 6. Have main retrieve the returned value: Use the variable RtnValue since you don't know which thread has exit-ed. o pthread_join(_______, ________________); 7. Have main print which thread exit-ed and the integer returned: o printf("Thread %d exited with value = %d\n", _____________________, _____________________);
1. strcpy( S1.Name, "THREAD 1" ); 2. pthread_create(&tid,NULL,FooBar, void *S1); 3. printf("The Name Received = %s\n", ((struct Shared*)arg)->Name ); 4. ((struct Shared*)arg)->Value = 2 * pthread_self(); 5. pthread_exit( arg ); 6-7. Even though pthread_join() can be used to wait for a specific thread; there is no way to wait for "any" thread by using the Pthreads library in Linux.
What does # signify in a shell script?
A comment
Which of the following strategies are used for deadlock prevention (circle all that apply)? A. Processes request all of the resources they need at once. They either get it all or get nothing and wait until they are all available. B. If a process needs to acquire a new resource, it must first release all resources it holds, then reacquire all it needs C. Remove the mutual exclusion condition on all of the resources D. Do not let any process hold more than 2 resources at any time. E. Resources are numbered sequentially in a total order. A process X can only ask for Rj if Rj > Ri forall Ri that X is currently holding.
A, B, E
Why are context switches considered undesirable (to be minimized) by OS designers?
Because context switches waste a considerable amount of CPU time when they save and load the state of the processes.
When a process resumes execution after returning from a fork(), how can it tell if it is the original process or the new one?
By the process ID which is returned by the fork() call. If it is equal to 0, it is the new one (child process); if it is a non-zero positive value, it is the original process.
What information is saved and restored during a context switch? Please give as much detail as possible.
Context switch requires saving the state of the old process and loading the saved state for the new process. Process state minimally includes current contents of registers, program counter, stack pointer, file descriptors, etc.Q. TRUE or FALSE? Context switch means a process switching from a ``blocked state'' to ``ready state''.A: FalseQ. TRUE or FALSE? In the ``zombie'' state, the process no longer exists but it leaves a record for its parent process to collect.A: TRUE
What are the main goals today in the design of operating systems?
Convenience for user, efficient utilization of the computerresources (CPU, memory, I/O devices), and expandibility.
Does this code provide a correct and fair solution for the readers/writers problem?
Even though this code is correct, it does not provide a fair solution. With the way it is written, there is a possibility that writers may starve readers if they arrive one after another. In other words, readers may never get a chance to enter the critical section (i.e. access the shared resource) if the writers don't take a break.
True False A thread may share a program counter with its parent.
FALSE
True or False A forked process may share a Run-Time Stack with its parent
FALSE
How does a thread acquire RAM that is NOT shared with other threads in the task?
Define local variables and use them only in this thread scope.
Determine the output for these commands: variable="Dennis" echo "$variable"
Dennis
In dining philosophers problem, why examining and acquiring a fork is done inside a critical section? Explain by giving an example what may go wrong if critical section is not used.
Each fork is shared by two neighboring philosophers. If it is not handled inside a critical section, both philosophers may think that they acquired the same fork and start eating using the same fork. This situation leads to an incorrect simulation.
True or False A forked process shares its parent's data space at all times.
FALSE
True or False Multiprogramming (having more programs in RAM simultaneously) decreases total CPU efficiency (in comparison to Uniprogramming or Batch processing)
FALSE. It increases CPU efficiency (see question above)
True or False? An acceptable solution for implementing mutual exclusion is to let the users disable interrupts before entering a critical section and enable them after leaving the critical section.
False
True or False? Even if mutual exclusion is not enforced on a critical section, results of multiple execution is deterministic (i.e. it produces the same results each time it runs).
False
True or False? If mutual exclusion is not enforced in accessing a critical section, a deadlock is guaranteed to occur.
False
True or False? In Producer/Consumer problem access to shared buffer must be done in a critical section, but access to ``in'' and ``out'' pointers doesn't need to be done inside a critical section.
False. "in" and "out" are shared variables. They need to be accessed inside a critical section.
True or False If a process uses up its allocated time slot, a timer interrupt occurs and the process is placed in a BLOCKED Queue.
False. It is placed in the READY queue.
True or False In Readers/Writers problem, it is possible to write code which is functionally correct but may lead to the starvation of writers. However, it is impossible to write the code such that readers may starve instead of writers.
False. It is possible to write such code.
True or False? One of the solutions proposed for handling the mutual exclusion problem relies on the knowledge of relative speeds of processes/processors.
False. No solution should rely on such assumptions
True or False Unlike time sharing systems, the principal objective of batch processing systems is to minimize response time.
False. Principal objective for time sharing is to minimize response time. Whereas, the principal objective for batch processing is to maximize processor use.
What are the important differences between a unix fork() and pthread_create()?
Fork(): child process has the separate data space with parent process, but they have the same code space. pthread_create(): threads share data space, code space, and os resources, but they have the unique thread ID, register state, stack and priority, PC counter.
In a uniprocessor environment, threads waiting for a lockalways sleep rather than spin. Why is this true (and reasonable)?
In a uniprocessor system, only one thread can run at a time. If a threadis spinning for a lock, it is doing nothing but wasting CPU cycles whilewaiting for the lock to become available. Instead, it is better that theysleep (in the blocked queue) while waiting so that others can use the CPU.When the lock becomes available, OS will wake them up.
True or False? If we constrain the resource requests in such a way that no cycle can occur in the process-resource graph, then deadlock can be prevented permanently.
True
What is a critical section i.e. what makes a section 'critical'?
In an asynchronous procedure of a computer program, a part that can not be executed simultaneously with an associated critical section of another asynchronous procedure. In general, a code segment in which shared variables, shared file descriptors (shared resources) are accessed is considered a critical section.
True or False? While DMA (Direct Memory Access) is taking place, processor is free to do other things. The processor is only involved at the beginning and end of the DMA transfer.
True
What does it mean to say that "pthread_mutex_lock(...) is a blocking call"?
If the mutex lock requested by this call is held by anotherprocess, the called will be blocked until the lock is released by thecurrent owner (via executing a pthread_mutex_unlock() call)
In dining philosophers problem, which senario may lead to a deadlock situation?
If the simulation code is written in such a way that each philosopher first acquires the right fork and then attempts to acquire the left fork, a deadlock may occur. Because it is possible that philosophers may enter a circular wait situation in which each one holds the fork on the right and tries to get the fork on the left (which will never happen).
Explain under what circumstances a spinlock might be less efficient than the alternative.
In uniprocessor systems, processes can use CPU one at a time. If a process is "busy waiting" for a long time, then a spinlock might be less efficient.
What does #! signify in a shell script?
It's a special notation which tells the shell, "After this mark, read the name of the script interpreter i want to use."
Who are the 2 individuals generally credited with the invention of C/Unix?
Ken Thompson and Dennis Ritchie.
What does it mean to say that a library or a module is MT-Safe?
MT-Safe : MultiThread-Safe which means that the behavior of the function is stable when two threads try to use it at the same time.In other words, a library/module protects its global and static data with locks and can provide a reasonable amount of concurrency.
What is an alternative to spinlocking?
Put the process in a wait queue, so it doesn't waste CPU cycles andallow it to sleep until the block is released.
What is the difference between starvation and deadlock?
STARVATION: A condition in which a process is indefinitely delayed because other processes are always given preference.DEADLOCK: An impasse that occurs when multiple processes are waiting for the availability of a resource that will not become available because it is being held by another process that is in a similar state.
Early system designers wanted to increase CPU efficiency by increasing the number of programs in memory from 1 to some small n. Explain the reasoning behind that goal; ie. why would having more programs in RAM increase total CPU efficiency?
Since several jobs can be kept simultaneously in memory, when one jobneeds to wait, the CPU is switched to another job and execute it. After thefirst job finishes its waiting, it can get the CPU back. Thus therewill always be some jobs resident in memory and ready to execute, theCPU will never be idle. Since the programs are resident in RAM,the overhead associated with task switching will be small.
In UNIX/Linux, the command ``ls | grep ercal > grep '' does the following:
Stores those lines in the file listing of the current directory which contains the string ``ercal'' into a file called ``grep''.
True False A thread may share a File Descriptor Table with its parent
TRUE
True False A thread may share code space with its parent.
TRUE
True False A thread may share data space with its parent.
TRUE
True or False A forked process may share code space with its parent.
TRUE
True or False In the specification of pthread_join() in Linux, there is no way to wait for "any" thread (i.e. the call should specify a particular thread_id to join)
TRUE
True or False? If the shared resources are numbered 1 through N and a process can only ask for resources that are numbered higher than that of any resource that it currently holds, then deadlock can never happen.
TRUE
True False ? LINUX is designed as a monolithic kernel.
TRUE. But, with a new twist for expanding OS functionality: LINUXsupports dynamically installable modules. A module can be compiled andinstalled on a running version of the kernel. This is accomplished byproviding system calls to install/remove modules.
How does a user process get privileged operations performed?
The hardware allows privileged instructions to be executed only in supervisor mode. If an attempt is made to execute a privileged instruction in user mode, the hardware does not execute theinstruction, but rather treats the instruction as illegal and traps to the OS and automatically switches to supervisor mode. When a user program does a system call, the switch to the supervisor mode is done automatically by the OS and the priviledged instructions that are needed by the system routine can be executed. Since the OS code is trusted, there is no harm done by giving access to privilidged instructions this way.
What happens when you put '&' at the end of a command line in Linux? Explain this in terms of the shell's behavior.
The shell executes the Linux command in the background
Why does a machine need dual mode operation?
To ensure proper operation, we must protect the operating system and allthe programs and their data from any malfunctioning program.The protection is accomplished by designating some of the machineinstructions that may cause harm as "privileged" instructions.Dual mode operations can protect the OS from errant users, and the users from one another.It also prevents the abuse of priviledged instructions (such as 'interrupt enable/disable')by the user programs.
What was the original purpose/goal in the design of operating systems?
To increase the efficiency of hardware.
True or False? If there is no mutual exclusion condition for any resource in the system, then there is no possibility for deadlock.
True
What is dual mode operation?
User mode vs. supervisor mode.
Write a shell statement which divide 3 / 2 and stores the answer in $average
average=$(echo '3 / 2' | bc)
Create a variable named bar which stores the output of the 'users' command.
bar=$(users)
Write a loop which reads the file 'foobar' into the variable 'lineIN' one line at a time
cat foobar | while read lineIN do ... done
Suppose i have a file which has a bunch of data separated by tabs. name a program that could return just one column
cut or awk
Which of the following would not necessarily cause a process to be interrupted? (a) Division by zero (b) reference outside user's memory space (c) page fault (d) accessing cache memory (e) end of time slice (f) none of the above
d
What is the function prototype for the POSIX pthread_create() call?
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg)
What does the command du do?
figures out disk usage (size of a directory)
Write the command which throws output and errors away while running the script foo.sh.
foo.sh >& /dev/null
Write the name of the system call for obtaining the process id of a process in UNIX?
getpid()
Write the name of the system call for obtaining the process id of a process' parent in UNIX?
getppid()
In UNIX, how do you display the lines that contain the string "smith" in the file "names.txt"?
grep smith names.txt
Write an if statement which compares $variable to the integer 5 to see if it is equal
if [ $variable -eq 5 ]
Explain the role of each semaphore used in this code.
mutex1: to provide mutually exclusive access to the shared variable "readcount" by multiple readers.mutex2: to provide mutually exclusive access to the shared variable "writecount" by multiple writers.readBlock: if a reader arrives while a writer is inside the critical section(CS) and other writers are waiting, this semaphore will cause that reader to get blocked until the last writer leaves the CS.writeBlock: This semaphore causes any writer to get blocked if there is one writer or reader(s) currently accessing the CS.
The word 'mutex' is short for ______________________________________.
mutual exclusion
How do you change the name of a file in Unix?
mv filename1 filename2
I've got a variable named flibble which contains the string 'tom Jerry harry'. write a command which stores just 'tom' into a new variable.
new=$(echo $flibble | cut -f1 -d' ')
Declare a string variable named oldguy which contains 'Dennis Ritchie' in the shell.
oldguy='Dennis Ritchie'
In UNIX, how do you display the list of processes that belong to the user "johns"?
ps -acefl | grep johns
Write a command which lists the processes that are owned by or contain the word foo in their name.
ps -ef | grep foo
Given int X[10]; some appropriate function MyFun pthread_t Tid; Write the call to pthread_create(), which executes MyFun, which accepts the array X as an argument
pthread_create(&Tid, NULL, MyFun, X)
What is the difference between pthread_mutex_lock and pthread_mutex_trylock?
pthread_mutex_lock is a blocking call. If we try to lock a mutex that is alreadylocked by some other thread, pthread_mutex_lock blocks until the mutex is unlocked.But pthread_mutex_trylock is a nonblocking function that returns if the mutex isalready locked.------------------------------------------------------------------------------------------The code below is written to provide one possible solution to the READERS/WRITERS problem.------------------------------------------------------------------------------------------int readCount=0, writeCount=0;semaphore mutex1=1, mutex2=1;semaphore readBlock=1, writeBlock=1,reader() { while(TRUE) { <other computing>; P(readBlock); P(mutex1); readCount++; if(readCount == 1) P(writeBlock); V(mutex1); V(readBlock); access(resource); P(mutex1); readCount--; if(readCount == 0) V(writeBlock); V(mutex1); }}writer() { while(TRUE) { <other computing>; P(mutex2); writeCount++; if(writeCount == 1) P(readBlock); V(mutex2); P(writeBlock); access(resource); V(writeBlock); P(mutex2) writeCount--; if(writeCount == 0) V(readBlock); V(mutex2); }}---------------------------------------------------------------------Answer the following questions based on the code given above.---------------------------------------------------------------------
What is the required function prototype for the function MyFun()?
void* MyFun( void* X )
Give an example event for each transition to occur.(You need to give at least five example events).
{create process}: user starts a new process or a program issues a fork() or a pthread_create() call. {cpu available}: the process currently occupying CPU stops running and the process in front of the READY queue is scheduled to run {time expires}: currently running process uses up its alloted time slot for this turn (timer interrupt). {event wait}: the process issues an I/O read {event completed}: DMA controller interrupts CPU signalling the completion of an I/O read {exit system}: process terminates or segmentation fault
