Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create special files of type socket?

Tags:

unix

gdb

I need to create serial port socket for kgdb-gdb remote connection.

Just as mkfifo creates a FIFO on your system, how can we create socket files?

like image 613
Sandeep Singh Avatar asked May 17 '11 02:05

Sandeep Singh


People also ask

How do I create a .sock file?

To create a UNIX domain socket, use the socket function and specify AF_UNIX as the domain for the socket. The z/TPF system supports a maximum number of 16,383 active UNIX domain sockets at any time. After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function.

Is a socket just a file?

There is no difference between a socket (descriptor) and a file descriptor(s). A socket is just a special form of a file. For example, you can use the syscalls used on file descriptors, read() and write(), on socket descriptors.

What is socket file type?

A socket is a special file used for inter-process communication, which enables communication between two processes. In addition to sending data, processes can send file descriptors across a Unix domain socket connection using the sendmsg() and recvmsg() system calls.

Where do I put a socket file?

They are to be stored in /run/ according to the Filesystem Hierarchy Standard (FHS).


1 Answers

The link in the accepted answer by @cidermonkey is great if you're trying to write an app that uses sockets. If you literally just want to create one you can do it in python:

~]# python -c "import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('/tmp/somesocket')" ~]# ll /tmp/somesocket  srwxr-xr-x. 1 root root 0 Mar  3 19:30 /tmp/somesocket 

Or with a tiny C program, e.g., save the following to create-a-socket.c:

#include <fcntl.h> #include <sys/un.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h>  int main(int argc, char **argv) {     // The following line expects the socket path to be first argument     char * mysocketpath = argv[1];     // Alternatively, you could comment that and set it statically:     //char * mysocketpath = "/tmp/mysock";     struct sockaddr_un namesock;     int fd;     namesock.sun_family = AF_UNIX;     strncpy(namesock.sun_path, (char *)mysocketpath, sizeof(namesock.sun_path));     fd = socket(AF_UNIX, SOCK_DGRAM, 0);     bind(fd, (struct sockaddr *) &namesock, sizeof(struct sockaddr_un));     close(fd);     return 0; } 

Then install gcc, compile it, and ta-da:

~]# gcc -o create-a-socket create-a-socket.c ~]# ./create-a-socket mysock ~]# ll mysock srwxr-xr-x. 1 root root 0 Mar  3 17:45 mysock 
like image 103
rsaw Avatar answered Sep 19 '22 13:09

rsaw