Last active
August 29, 2015 13:57
-
-
Save wangrenjun/9803449 to your computer and use it in GitHub Desktop.
linux splice simple test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* No license provided. | |
*/ | |
#define _GNU_SOURCE | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
// gcc ./testsplice.c -o ./testsplice.out | |
int zcopy(int dstfd, int srcfd, loff_t offset, size_t size) | |
{ | |
int filedes[2]; | |
int ret; | |
size_t to_write = size; | |
ret = pipe(filedes); | |
if (ret < 0) | |
goto out; | |
if (to_write == (size_t) -1) { | |
struct stat buf; | |
fstat(srcfd, &buf); | |
to_write = size = buf.st_size; | |
} | |
while (to_write > 0) { | |
ret = splice(srcfd, &offset, filedes[1], NULL, to_write, SPLICE_F_MORE | SPLICE_F_MOVE); | |
if (ret < 0) | |
goto pipe; | |
else if (ret == 0) | |
break; | |
else | |
to_write -= ret; | |
} | |
to_write = size - to_write; | |
while (to_write > 0) { | |
ret = splice(filedes[0], NULL, dstfd, NULL, to_write, SPLICE_F_MORE | SPLICE_F_MOVE); | |
if (ret < 0) | |
goto pipe; | |
else | |
to_write -= ret; | |
} | |
pipe: | |
close(filedes[0]); | |
close(filedes[1]); | |
out: | |
if (ret < 0) { | |
perror("Something wrong"); | |
return -1; | |
} | |
return 0; | |
} | |
int main() | |
{ | |
int dstfd, srcfd; | |
srcfd = open("./src.txt", O_RDONLY, 0); | |
if (srcfd == -1) { | |
perror("Failed to open"); | |
exit(EXIT_FAILURE); | |
} | |
dstfd = open("./dest.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); | |
if (dstfd == -1) { | |
perror("Failed to create"); | |
exit(EXIT_FAILURE); | |
} | |
zcopy(dstfd, srcfd, 0, 1024); | |
dstfd = open("./dest2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); | |
if (dstfd == -1) { | |
perror("Failed to create"); | |
exit(EXIT_FAILURE); | |
} | |
zcopy(dstfd, srcfd, 0, -1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment