dup函数的使用
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fd = open("temp", O_RDWR | O_CREAT | O_TRUNC, 0664);
if(fd == -1)
{
perror("open");
exit(1);
}
int fd1 = dup(fd);
char *p = "this is dup demo";
printf("sizeof--%lu---\n", sizeof("this is dup demo"));
printf("strlen--%lu---\n", strlen("this is dup demo"));
write(fd1, p, strlen(p)+1);
close(fd1);
char buf[64]= { 0 };
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
printf("buf = %s\n", buf);
close(fd);
}
测试结果
dup2函数使用
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fd = open("temp", O_RDWR | O_CREAT | O_APPEND, 0664);
if(fd == -1)
{
perror("open");
exit(1);
}
int fd2 = open("temp1", O_RDWR | O_CREAT | O_APPEND, 0664);
if(fd2 == -1)
{
perror("open-2");
exit(1);
}
dup2(fd, fd2);
char *p = "this is dup2 demo....";
write(fd2, p, strlen(p)+1);
close(fd2);
char buf[64]= { 0 };
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
printf("buf = %s\n", buf);
close(fd);
}
测试结果
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFF (1024)
int my_copy(int fd_in, int fd_out)
{
int fd_r = fd_in;
int fd_w = fd_out;
char buf[BUFF] = { 0 };
int ret = 0;
memset(buf, 0, sizeof(buf));
while((ret = read(fd_r, buf, BUFF)) > 0)
{
write(fd_w, buf, ret);
}
close(fd_r);
close(fd_w);
return 0;
}
int main(int argc, const char *argv[])
{
int ret = -1;
int fd = -1;
int i = 0;
int flag = 0;
if(argc < 2)
{
fprintf(stderr, "Usage %s [+/-] <src_file>!\n", argv[0]);
return -1;
}
for(i=1; i<argc; i++)
{
if(0 == strcmp(argv[i], "+"))
{
fd = open(argv[++i], O_RDONLY);
if(fd < 0)
{
perror("open fd_in");
return -2;
}
if(STDIN_FILENO != dup2(fd, STDIN_FILENO))
{
return -3;
}
close(fd);
}
else if(0 == strcmp(argv[i], "-"))
{
fd = open(argv[++i], O_WRONLY | O_CREAT | O_TRUNC, 0777);
printf("fd =%d\n", fd);
if(fd < 0)
{
perror("open fd_in");
return -2;
}
if(STDOUT_FILENO != dup2(fd, STDOUT_FILENO))
{
printf("dup2 error!\n");
return -3;
}
close(fd);
}
else
{
flag = 1;
fd = open(argv[i], O_RDONLY);
if(fd < 0)
{
perror("open fd_in");
return -5;
}
if(STDIN_FILENO != dup2(fd, STDIN_FILENO))
{
printf("dup2 error3!\n");
return -6;
}
my_copy(STDIN_FILENO, STDOUT_FILENO);
close(fd);
}
}
if(!flag)
my_copy(STDIN_FILENO, STDOUT_FILENO);
return 0;
}
测试结果