如何创建socket类型的特殊文件?

发布于 2024-11-07 19:45:08 字数 94 浏览 0 评论 0原文

我需要为 kgdb-gdb 远程连接创建串行端口套接字。

正如mkfifo在您的系统上创建一个FIFO一样,我们如何创建套接字文件?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可爱咩 2024-11-14 19:45:08

如果您尝试编写一个使用套接字的应用程序,@cidermonkey 接受的答案中的链接非常有用。如果你真的只是想创建一个,你可以用 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

#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:

~]# 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文