Search code examples
csocketsunix-socket

Temporary file for unix domain socket


I create temporary file for unix domain socket.

int fd;
char sf[] = {"/tmp/socket-XXXXXX"};

if ((fd = mkstemp(sf)) == -1)
    exit(SOCKFERR);
close(fd);

Buf when I assigns the address to the socket I need remove this file (bind() function works only if file which will socket file doesn't exist yet).

int sfd;
struct sockaddr_un addr;

if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
    exit(SOCKERR);  

unlink(sf);
memset(&addr, 0, sizeof(struct sockaddr_un));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, 108, sf);   /* 108 is length of add.sun_path */

if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) != 0)
    exit(BINDERR);

How can I create temporary file for unix domain socket without removing it before bind()?


Solution

  • How can I create temporary file for unix domain socket without removing it before bind()?

    It is not possible. Everything in linux is a file. "Socket" is a "socket file". With mkstemp you create what is called a "regular file" or a "normal file".

    If you create a regular file and try to create a directory with the same path, you will get an error EEXISTS. You have to remote the file, then create a directory.

    Exactly same happens when you try to create a socket file with the same name as existing regular file - the file already exists there. When you try to create a symbolic link or a hard link or a "character device" ("character special file") or any other file type. You have to remove the preexisting file, then create the other file type.