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);
}
// copy fd
int fd1 = dup(fd);
// write file
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);
// read file
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);
}
// copy fd
dup2(fd, fd2);
// write file
char *p = "this is dup2 demo....";
write(fd2, p, strlen(p)+1);
close(fd2);
// read file
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;
}
测试结果
版权声明:本文为zxy131072原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。