Linux

[Linux, C] 파일 디스크립터 생성

반나무 2020. 10. 19. 15:56
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void error_handling(char *message);

int main(void){
        // socket1,2
        int sd1, sd2;

        // fd1,2
        int fd1, fd2;

        // buffer
        char buf[] = "end\n";

        // socket1, fd1
        sd1 = socket(PF_INET, SOCK_STREAM, 0);
        fd1 = open("test1.dat", O_CREAT | O_RDONLY, 0755);

        // socket2, fd2
        fd2 = open("test2.dat", O_CREAT | O_WRONLY ,0733);
        sd2 = socket(PF_INET, SOCK_DGRAM, 0);

        write(fd2, buf, 4);

        if(fd2 == -1)
                error_handling("open() error!");

        // descritor print
        printf("file descriptor: %d \n", fd1);
        printf("file descriptor: %d \n", fd2);
        printf("socket descriptor : %d \n", sd1);
        printf("socket descriptor : %d \n", sd2);

        close(sd1);
        close(sd2);
        close(fd1);
        close(fd2);

        return 0;

}

void error_handling(char *message){
        fputs(message, stderr);
        fputc('\n', stderr);
        exit(1);
}
반응형