Commit 8d7a1aa2 authored by Happy's avatar Happy
Browse files

add syscall-filesystem dup2, copy old fd to new fd

No related merge requests found
Showing with 46 additions and 0 deletions
+46 -0
......@@ -38,4 +38,5 @@
#define SYS_thread_join 34
#define SYS_getppid 35
#define SYS_execve 36
#define SYS_dup2 37
#endif
\ No newline at end of file
......@@ -111,6 +111,7 @@ argstr(int n, char *buf, int max)
extern uint64 sys_chdir(void);
extern uint64 sys_close(void);
extern uint64 sys_dup(void);
extern uint64 sys_dup2(void);
extern uint64 sys_exec(void);
extern uint64 sys_execve(void);
extern uint64 sys_exit(void);
......@@ -159,6 +160,7 @@ static uint64 (*syscalls[])(void) = {
[SYS_fstat] sys_fstat,
[SYS_chdir] sys_chdir,
[SYS_dup] sys_dup,
[SYS_dup2] sys_dup2,
[SYS_getpid] sys_getpid,
[SYS_getppid] sys_getppid,
[SYS_sbrk] sys_sbrk,
......@@ -199,6 +201,7 @@ static char *sysnames[] = {
[SYS_fstat] "fstat",
[SYS_chdir] "chdir",
[SYS_dup] "dup",
[SYS_dup2] "dup2",
[SYS_getpid] "getpid",
[SYS_getppid] "getppid",
[SYS_sbrk] "sbrk",
......
......@@ -58,6 +58,30 @@ fdalloc(struct file *f)
return -1;
}
//如果目标文件描述符 new 已被占用,关闭目标文件描述符
//分配目标文件描述符 new,将 old 文件描述符复制到目标位置
static int
fdalloc_new(struct file *f, int new)
{
struct proc *p = myproc(); // 获取当前进程结构
// 检查文件描述符范围是否合法
if (new < 0 || new >= NOFILE) {
return -1; // 文件描述符超出范围
}
// 如果目标描述符已经被占用,先关闭它
if (p->ofile[new] != 0) {
fileclose(p->ofile[new]); // 关闭旧文件
p->ofile[new] = 0; // 清空描述符表对应的条目
}
// 分配新的文件描述符
p->ofile[new] = f; // 将目标文件描述符指向文件 `f`
return new; // 返回目标文件描述符
}
uint64
sys_dup(void)
{
......@@ -72,6 +96,22 @@ sys_dup(void)
return fd;
}
uint64
sys_dup2(void)
{
struct file *f;
int new;
int fd;
if(argfd(0, 0, &f) < 0 || argint(1, &new) < 0)
return -1;
if((fd=fdalloc_new(f, new)) < 0)
return -1;
filedup(f);
return fd;
}
uint64
sys_read(void)
{
......
......@@ -23,6 +23,7 @@ int fstat(int fd, struct stat*);
int mkdir(const char *dirname);
int chdir(const char *dirname);
int dup(int fd);
int dup2(int oldfd,int newfd);
int getpid(void);
int getppid(void);
char* sbrk(int size);
......
......@@ -30,6 +30,7 @@ entry("fstat");
entry("mkdir");
entry("chdir");
entry("dup");
entry("dup2");
entry("getpid");
entry("getppid");
entry("sbrk");
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment