Copia con System Calls write/read
27 Maggio 2011NB: a parità di grandezza di file copiato, questo utilizzo delle system calls è circa il 40% più lento dell’utilizzo della chiamata sendfile del programma Fast Copy
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/stat.h>
int main (int argc, char** argv)
{
int src; /* file descriptor for source file */
int dest; /* file descriptor for destination file */
struct stat stat_buf; /* hold information about input file */
int rc; /* return code from sendfile */
int loop; /* counts how many times the file has been copied */
double sumoftimes=0.0;
char buffer[BUFSIZ];
struct timeval tv;
struct timeval start_tv;
/* check for two command line arguments */
if (argc != 4) {
fprintf(stderr, "usage: %s <source> <destination> <repetitions>\n", argv[0]);
exit(1);
}
/* copy file using write */
for(loop=0; loop<atoi(argv[3]); loop++)
{
/* check that source file exists and can be opened */
src = open(argv[1], O_RDONLY);
if (src == -1) {
fprintf(stderr, "unable to open '%s': %s\n", argv[1], strerror(errno));
exit(1);
}
/* open destination file */
dest = open(argv[2], O_WRONLY|O_CREAT, stat_buf.st_mode);
if (dest == -1) {
fprintf(stderr, "unable to open '%s': %s\n", argv[2], strerror(errno));
exit(1);
}
gettimeofday(&start_tv, NULL);
while((rc=read(src, buffer, BUFSIZ)) > 0 )
{
write(dest, buffer, rc);
}
gettimeofday(&tv, NULL);
sumoftimes += (tv.tv_sec - start_tv.tv_sec) + (tv.tv_usec - start_tv.tv_usec) / 1000000.0;
/* print walkthrough */
fprintf(stdout, "[%d/%s] %f %f %f\n", loop, argv[3], tv.tv_sec+(tv.tv_usec/ 1000000.0), start_tv.tv_sec+(start_tv.tv_usec / 1000000.0), sumoftimes);
close(dest);
close(src);
unlink(dest);
unlink(src);
}
fprintf(stdout, "\nTempi di esecuzione [totale, prove, media]: %f %s %f secondi\n", sumoftimes, argv[3], sumoftimes/atoi(argv[3]));
return 0;
}
syntax highlighted by Code2HTML, v. 0.9.1
syntax highlighted by Code2HTML, v. 0.9.1