如何从另一个范围访问 unistd write?

问题描述

我试图在声明了另一个“写入”函数的类中使用 unistd.h write,但我不知道我应该使用哪个范围解析器,因为 unistd 不是库,所以 unistd ::write() 不起作用。

如何从函数内部调用它?

// this won't compile

#include <stdio.h> // printf
#include <fcntl.h> 
#include <sys/stat.h> 
#include <unistd.h> 


class Fifo {
public:
    void write(const char* msg,int len);
};

void Fifo::write(const char* msg,int len) {
    int fd; 
    const char* filename = "/tmp/fifotest"; 
    mkfifo(filename,0666); 
    fd = open(filename,O_WRONLY|O_NONBLOCK);
    write(fd,msg,len); 
    close(fd); 
}   

int main() 
{ 
    Fifo fifo;
    fifo.write("hello",5);
    return 0;
} 

解决方法

所以使用未命名的范围 write

write(fd,msg,len);

等于

this->write(fd,len); 

writeFifo::write 函数中解析为 Fifo。做:

::write(fd,len); 

使用全局范围。喜欢:

#include <cstdio> // use cstdio in C++
extern "C" {      // C libraries need to be around extern "C"
#include <fcntl.h> 
#include <sys/stat.h> 
#include <unistd.h> 
}
class Fifo {
public:
    void write(const char* msg,int len);
};
void Fifo::write(const char* msg,int len) {
    int fd; 
    const char* filename = "/tmp/fifotest"; 
    mkfifo(filename,0666); 
    fd = open(filename,O_WRONLY|O_NONBLOCK);
    ::write(fd,len);  //here
    close(fd); 
}   
int main() { 
    Fifo fifo;
    fifo.write("hello",5);
    return 0;
}

研究 C++ 中的作用域、命名空间和作用域解析运算符以获取更多信息。