NEXT UP previous
Next: My Home Page

Answers

  1. In order to solve this problem you will need to keep a track of those file descriptors you take into service before you reach the file descriptor you want, so that you can release them again afterwards. The basic function appears as:

    	#include <linux/limits.h>
    
    	int mydup2(int oldfd, int newfd)
    	{
    	`	int i, fd, fdtable[OPEN_MAX];
    
    		if (newfd<0 || newfd>OPEN_MAX) 
    			return -1;
    
    		if (oldfd<0 || oldfd>OPEN_MAX) 
    			return -1;
    
    		if (newfd==oldfd) 
    			return newfd;
    
    		for (i = 0; i<OPEN_MAX; ++i> 
    			if (fdtable[i])
    
    		close (newfd);
    
    		while ((fd = dup(oldfd))!=newfd && fd!=-1) 
    			fdtable[fd] = 1;
    
    		for (i = 0; i<OPEN_MAX; ++i>)
    			if (fdtable[i])
    				close(i);
    
    		return fd;
    	}
    


  2. This is just a case of creating a pipe, setting it O_NONBLOCK and then counting and writing bytes into it until the write() call indicates, by its return value, that bytes are no longer being stored in the pipe. Looking at the source code a pipe should be 4 K.

  3. A pseudo code program to perform this task could be:
    	create pipe 
    	if (fork())
    	In parent, open() file 
    	while not end of file
    		read a character and write it to the pipe 
    	else
    		In child
    		while not end of pipe data
    			read a character from pipe and discard
    
    You should run this program a couple of times to make sure that the file you are copying is all stored in the buffer cache - it is much faster to read from memory than from disk.

  4. This program will be similar to the previous one except that you will create a shared memory segment instead of a pipe and then shmat() to the segment from within the parent and child processes after the fork() call. The extra problem with a shared memory solution is that you will need some form of synchronization between the two processes, so that the writer will not overwrite the character being transferred before the reader has read it, and vice-versa. An obvious way to do this is to use a semaphore which you can either implement yourself in shared memory or you could use the semaphore IPC mechanism provided. I leave you to do the experiment to work out which solution to the problem will be faster, pipes or shared memory.

NEXT UP previous
Next: My Home Page