Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用fcntl实现dup和dup2_C_Linux_Multithreading_Call_Fcntl - Fatal编程技术网

使用fcntl实现dup和dup2

使用fcntl实现dup和dup2,c,linux,multithreading,call,fcntl,C,Linux,Multithreading,Call,Fcntl,我正在使用fcntl实现dup和dup2,我所编码的是: int dup(int oldfd) { return fcntl(oldfd, F_DUPFD, STDERR_FILENO); } int dup2(int oldfd, int newfd) { if(oldfd == newfd) return oldfd; if(fcntl(oldfd, F_GETFD) == -1) return -1; if(close

我正在使用
fcntl
实现
dup
dup2
,我所编码的是:

int dup(int oldfd) {
    return fcntl(oldfd, F_DUPFD, STDERR_FILENO);
}

int dup2(int oldfd, int newfd) {

    if(oldfd == newfd)
        return oldfd;

    if(fcntl(oldfd, F_GETFD) == -1)
        return -1;

    if(close(newfd) == -1 && errno != EBADF)
        return -1;

    fcntl(oldfd, F_DUPFD, newfd);

    return newfd;
}
但是我发现dup2根本没有效率(太多的系统调用==>太多的内核模式切换),dup2也不是线程安全的,我认为可能会发生争用情况,因为如果在关闭(newfd)fcntl(oldfd,F_DUPFD,newfd)之间另一个线程接管控制并打开一个文件,文件描述符newfd可能会被接管


那么,如何使dup2更加高效和线程安全?

“我必须”。为什么?这是家庭作业吗?不可能使这个线程安全。是的,这是一个家庭作业,我认为不可能使它线程安全是答案的一部分。把它变成一个系统调用怎么样?说真的,存在系统调用是有原因的,避免多个系统调用和竞争条件就是其中的一些原因。