Skip to content

Commit

Permalink
Step 3: PipeCopy
Browse files Browse the repository at this point in the history
  • Loading branch information
cnphil committed Apr 5, 2013
1 parent 3258075 commit c28fda5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 1 deletion.
Binary file added PipeCopy
Binary file not shown.
57 changes: 57 additions & 0 deletions PipeCopy.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include "cse356header.h"

main(int argc, char *argv[])
{
pid_t forkpid;
int fd[2];

pipe(fd);
forkpid = fork();

if(forkpid == -1) {perror("fork"); exit(1);}

if(forkpid == 0) { // child process, reads
close(fd[0]); // closes the input side of the pipe

FILE *src;

src = fopen(argv[1], "r");

if(src == NULL) {
printf("Error: Could NOT open file \"%s\".\n", argv[1]);
exit(-1);
}

char *buffer[256];
while (true) {
int read_chars = fread(buffer, sizeof(char), 255, src);
if(read_chars <= 0) break;
write(fd[1], buffer, read_chars);
}
fclose(src);
exit(0);
} else { // parent process, writes
close(fd[1]);
wait(NULL);

FILE *dest;

dest = fopen(argv[2], "w+");

if(dest == NULL) {
printf("Error: Could NOT open file \"%s\".\n", argv[2]);
exit(-1);
}

// copying begins
char *buffer[256];
while (true) {
int read_chars = read(fd[0], buffer, sizeof(buffer));
if(read_chars <= 0) break;
fwrite(buffer, sizeof(char), read_chars, dest);
}
fclose(dest);

exit(0);
}
}
6 changes: 5 additions & 1 deletion makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
all: MyCopy ForkCopy
all: MyCopy ForkCopy PipeCopy
clear:
rm *.o
MyCopy: MyCopy.o
Expand All @@ -9,3 +9,7 @@ ForkCopy: ForkCopy.o
g++ ForkCopy.o -o ForkCopy
ForkCopy.o:
g++ -c ForkCopy.c
PipeCopy: PipeCopy.o
g++ PipeCopy.o -o PipeCopy
PipeCopy.o:
g++ -c PipeCopy.c

0 comments on commit c28fda5

Please sign in to comment.