File copy program using pipe between parent and child process in C

Starting the Operating Systems ‘category’ with this program.
Problem statement:-
Design a file copying program named FileCopy using ordinary pipes. This program will be passed two parameters : the first is the name of the file to be copied and the second is the name of the copied file. The program will then create an ordinary pipe and write the contents of the file to be copied to the pipe. The child process will read this file from the pipe and write it to the destination file.
For example, if we invoke the program as follows
FileCopy input.txt copy.txt


int main( int argc, char* argv[] ) {
	int fdone[2];
	pid_t childid;

	char readBuff[50];
	char writeBuff[50];
	int readCounter;

	pipe( fdone );

	if( argc < 3 ) {
	    printf( "Atleast need 2 params " );

	int fileOpen = open( argv[1], 0 );
	int targetFile = open( argv[2], 0666 );
	if ( fileOpen == -1 || targetFile == -1 ) {
	    printf( "Opening file failed " );
	childid = fork();

	if( childid == 0 ) {
	    // inside the child prcocess
	    close( fdone[1] );

	    read( fdone[0], readBuff, sizeof( readBuff ) );
	    printf( "The recived string is : %s", readBuff );

	    //Writing to the target fileOpen
	    write( targetFile, readBuff, strlen( readBuff ) + 1 );
	} else {
	    // inside the parent process
	    close( fdone[0] );
	    // code to read from a text file

	    while( (readCounter = read( fileOpen, readBuff, sizeof( readBuff ) ) > 0 ) )  {
		write( fdone[1], readBuff, sizeof( readBuff ) );
	    close( fdone[1] );

Yay! Hope it gets someone in need.

3 thoughts on “File copy program using pipe between parent and child process in C

  1. Hello,

    Thanks for posting!

    From just running the program alone, I ran into 3 separate bugs.
    1) We need to loop on reading the pipe and writing to the file. This will also require adding an append option to the open function. In the current state only the first 50 chars get copied.

    2) Inside of the child process’ write call, the # of bytes to be copied should be strlen(readBuff) – 1 instead of +1. +1 will actually take 2 characters out of bounds.

    3) It is necessary to clear the readBuff inside of the parent process every time (using memset is most efficient) otherwise redundant from the previous readBuff will get written to the pipe.

    If you left the bugs in there for students to discover, I apologize and would like to delete this post.

    Thanks again for posting πŸ™‚


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s