Wednesday 27 April 2016

Interprocess communication - named and unnamed pipes


Unnamed pipes:

1) These are created by the shell automatically.


2) They are opened at the time of creation only.

3) They are unidirectional.


Unnamed pipes may be only used with related processes (parent/child or child/child having the same parent). They exist as long as their descriptors are open.



How pipe is created? pipe() requires array of descriptor as parameter. One for reading and another for writing.




Pipe is shared to exchange info between related processes. Example here is a parent and child exchanging information.






** This example is taken from man pipe



Output:

First parent process is executed, data is written into write end. Child reads it and outputs data stored in buffer.


1) After a new child process is created, both processes will execute the next instruction following the fork() system call. why?

Instruction pointer will be same for child and parent process. So they will start to execute next instruction following the fork system call.

2) Why parent has to wait until child terminates?

A process could go bad, might continue to use up system resources and user might want to kill that process. One effective way to kill such a zombie process is to kill parent process (kill ppid). 

wait(NULL) is used by parent process to wait for child termination.
syntax: int wait (int* childStatus)
If child process is available, PID of child is returned. But if child has already got terminated, 0 is returned. If NULL is passed to wait(), it means that the user is not bothered about debug information.

WEXITSTATUS(childstatus) returns exit status of the child

Named pipes(FIFO)

1) They are created using the command mkfifo.



write shown in above is a blocking system call. The process is put to sleep until read is complete. In other words, if I execute only fifo1, since the process is sleeping there is no output. Once another process reads the myfifo pipe, the process's work is done and is terminated.

2) They exists in the file system with a given file name.





3) They are Bi-directional.

Another process reads the same fifo file which was created earlier:

Executing write and then read, output is "Hi". But if only read process is executed, then output is 0, since no other process has written into the pipe[? I thought read is also blocking system call]



References:
https://delightlylinux.wordpress.com/2012/06/25/what-is-pid-and-ppid/
http://www.ibm.com/support/knowledgecenter/SSB23S_1.1.0.13/gtpc2/cpp_wait.html

http://www.allinterview.com/showanswers/79689/differentiate-between-named-unnamed-pipe.html

No comments:

Post a Comment