Search code examples
cunixposixsystem-callsxv6

What's the easiest workaround on the OS, which doesn't have the dup2 syscall?


I'm working with the xv6 OS and I need to substitute stdio with a file. This is normally done with the dup2 syscall, which this OS doesn't have. Is there any workaround? Do I have to implement my own syscall which will try to mimic the POSIX's one behavior? Or can the functionality I need (substitute the file descriptor) can be implemented in a regular function in a c program? Thanks.


Solution

  • dup2( filedes, filedes2 ); 
    

    means

    close( filedes2 );
    fcntl( filedes, F_DUPFD, filedes2 );
    

    You can do

    close(0);
    dup(fd);
    

    subject to race conditions, since dup2 atomic function but close and dup include two function calls.