如何创建套接字类型的特殊文件? [英] How to create special files of type socket?
本文介绍了如何创建套接字类型的特殊文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为 kgdb-gdb 远程连接创建串口套接字.
I need to create serial port socket for kgdb-gdb remote connection.
就像 mkfifo
在你的系统上创建一个 FIFO,我们如何创建套接字文件?
Just as mkfifo
creates a FIFO on your system, how can we create socket files?
推荐答案
如果您尝试编写使用套接字的应用程序,@cidermonkey 接受的答案中的链接非常棒.如果你真的只是想创建一个,你可以在 python 中完成:
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
或者用一个很小的C程序,例如,将以下内容保存到create-a-socket.c
:
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;
}
然后安装gcc,编译它,然后ta-da:
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
这篇关于如何创建套接字类型的特殊文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文