1.编写一个与3.12节dup2功能相同的函数。
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc,char *argv[]) {
int i;
int fd_src,fd_dest;
if(argc != 3)
{
fprintf(stderr,"usage %s src dest\n",argv[0]);
return -1;
}
fd_src = atoi(argv[1]);
fd_dest = atoi(argv[2]);
if (fd_src <= 0 || fd_dest <= 0 || fd_src > 256 || fd_dest > 256)
{
fprintf(stderr,"fd should be greater then 0 and less or equal 256\n");
return -1;
}
if(fd_src == fd_dest)
{
fprintf(stdout,"the new fd is %d\n",fd_dest);
return 0;
}
if(dup(fd_src) == -1)
{
fprintf(stderr,"the fd is not open\n");
return -1;
}
int fdarray[fd_dest];
int index;
close(fd_dest);
for(index = 0;index < fd_dest;index++)
{
fdarray[index] = dup(fd_src);
if(fdarray[index] == -1)
{
fprintf(stderr,"dup error\n");
return -1;
}
if(fdarray[index] == fd_dest)
fprintf(stdout,"dup success!the new fd is %d\n",fd_dest);
}
for(i = 0;i < index;i++)
close(fdarray[i]);
return 0;
}
2.编程实现cp功能。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char * argv[])
{
if(argc != 3)
{
fprintf(stderr,"usage:%s file1 file2\n",argv[0]);
return -1;
}
int fd1 = open(argv[1],O_RDONLY);
if(fd1 == -1)
{
fprintf(stderr,"can not open file %s\n ",argv[1]);
return -1;
}
int fd2 = open(argv[2],O_WRONLY | O_CREAT,0664);
char buffer[4096];
int n;
while((n = read(fd1,buffer,4096)) > 0)
write(fd2,buffer,n);
close(fd1);
close(fd2);
}