L8: Pipes/Signals Flashcards
dup:
Two Forms
and their use
Form 1:
new_fd = dup( old_fd );
When using the first form, the kernel picks a new file descriptor number and it is returned. It will be the smallest index that is not yet used for a file descriptor.
Form 2:
dup2( old_fd, new_fd);
The second form lets the programmer specify the new file descriptor number.
Either way, both old and new file descriptors now index the same value(file).
Method used to
duplicate a file descriptor
dup( old_fd )
or
dup2( old_fd, new_fd )
Pipe:
Read Rules
- If there is any data in the pipe, return it.
- It may be fewer bytes than requested
- If the pipe is empty, and there is a writer, wait for data to be added to the pipe
- Otherwise, return the value -1 (EOF)
Basic Types of
Inter-Process Communication (IPC) (2)
Pipes
Signals
Code Outline:
Setting up a pipe between
parent and child process
int fd[2]; //declare array for file descriptors
pipe(fd); //use the pipe function to create a pipe and set values for the file descriptors
if(fork() ){
//Parent Process - if parent is writing
close(fd[0] ); //Close the read end of the pipe
write( fd[1], “stuff to write”); //parent writes into pipe
// more work….
close( fd[1] ); // Finished, parent closes write end
}
else {
//Child Process - reads what parent has written
close( fd[1] ); // Closes the write end of the pipe
read( fd[0] ); // Read from the pipe
// more work
close ( fd[0] ); //finished, close the read end
}
What is a Pipe?
- A kernel buffer with a “read” end and a “write” end
- The kernel presents each end as a file descriptor
- Processes can use the pipe with normal read/write routines,
- One process writes
- Another process reads
- The writer waits if the buffer is full
- The reader waits if the buffer is empty
- A parent process creates file descriptors with the
- pipe() routine
- These descriptors are preserved during fork() and exec(), and can be used by a child process.