天天看點

socket 檔案描述符

Linux中,socket 也是被認為是檔案的一種

window中,需要區分socket和檔案

  • 檔案描述符:window中叫檔案句柄;可以了解成配置設定的ID
  • socket經過建立的過程中才會被配置設定檔案描述符

檔案操作

  • 打開檔案

    int open(const char *path, int flag)

    ,flag是打開的模式,多個模式用OR連接配接,傳回的就是檔案描述符。(#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>)
  • 關閉檔案

    int close(int fd)

    ,這個同樣可以關閉socket。(#include <unistd.h>)
  • 将資料寫入檔案:

    ssize_t write(int fd, const void *buf, size_t nbytes);

    ,(#include <unistd.h>)
  • size_t 是 unsigned int,ssize_t 是 signed int

讀寫檔案操作

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

void error_handling(char *message);

int main(void)
{
    int fd;
    char buf[] = "Let's go! \n";

    // 設定權限
    umask(0000);
    if(creat("data.txt", 0777) == -1)
        error_handling("creat() error\n");

    // 寫入資料
    fd = open("data.txt", O_CREAT|O_WRONLY|O_TRUNC);
    if(fd == -1)
        error_handling("write open() error\n");
    printf("file descriptor %d\n", fd);

    if(write(fd, buf, sizeof(buf)) == -1)
        error_handling("write() error\n");
    printf("write over.\n");
    
    close(fd);

    // 讀取資料
    fd = open("data.txt", O_RDONLY);
    if(fd == -1)
        error_handling("read open() error\n");

    char read_buf[100];
    if(read(fd, read_buf, sizeof(read_buf)) == -1)
        error_handling("read() error\n");
    printf("file data is %s\n", read_buf);

    close(fd);
    return 0;
}

void error_handling(char *message)
{
    perror(message);
    exit(1);
}
           

注:

  • 如果提示沒有權限,可以參考 Permission denied: https://blog.csdn.net/aicamel/article/details/80922459,在建立檔案的時候,設定權限
  • 這些檔案IO操作同樣适用于socket
  • 檔案描述符從3開始,從小到大編号,因為0、1、2被配置設定給了标準IO描述符

同時建立檔案和套接字,列印出對應的檔案描述符

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

void error_handling(char *message);

int main(void)
{
    int fd1, fd2, fd3;
    char *file_name = "data.dat";

    // 設定權限
    umask(0000);
    if(creat(file_name, 0777) == -1)
        error_handling("creat() error\n");

    fd1 = socket(PF_INET, SOCK_STREAM, 0);
    fd2 = open(file_name, O_CREAT|O_WRONLY|O_TRUNC);
    fd3 = socket(PF_INET, SOCK_STREAM, 0);

    printf("file descripor 1: %d\n", fd1);
    printf("file descripor 2: %d\n", fd2);
    printf("file descripor 3: %d\n", fd3);

    close(fd1);
    close(fd2);
    close(fd3);

    return 0;
}

void error_handling(char *message)
{
    perror(message);
    exit(1);
}
           

其他:

  • 常用的flag常量值:隻讀(O_RDONLY),隻寫(O_WRONLY),讀寫(O_RDWR),必要時建立檔案(O_CREAT),删除現有資料(O_TRUNC),追加模式(O_APPEND)
  • 0、1、2檔案描述符分别是标準輸入、輸出、錯誤