我正在尝试使用UNIX数据克套接字进行IPC,但我遇到了实现问题。我能够成功地执行UNIX流套接字,但我的程序的功能要求使用数据克。
以下是发送方的代码:
struct sockaddr_un remote;
struct sockaddr_un local;
socklen_t size_remote;
socklen_t size_local;
if(out_sock == -1)
{
if ((out_sock = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
{
perror("toYYYYY socket");
exit(1);
}
char remote_path[28] = "/tmp/sockets/fromXXXXXXX0000";
sprintf(remote_path + 24, "%d", portOffset + XXXXXX_CTRL_UDP_PORT);
memset(&remote, 0, sizeof(struct sockaddr_un));
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, remote_path);
size_remote = (offsetof(struct sockaddr_un, sun_path) + strlen(remote_path));
char local_path[28] = "/tmp/sockets/toYYYYY0000";
sprintf(local_path + 20, "%d", portOffset + XXXXXX_CTRL_UDP_PORT);
memset(&local, 0, sizeof(struct sockaddr_un));
local.sun_family = AF_UNIX;
strcpy(local.sun_path, local_path);
size_local = (offsetof(struct sockaddr_un, sun_path) + strlen(local_path));
unlink(local_path);
int rtv = bind(out_sock, (struct sockaddr *)&local, size_local);
if(rtv)
perror("toYYYYY bind");
}
written = sendto(out_sock, packet, bytes, 0, (struct sockaddr *)&remote, size_remote);
if (written != bytes)
{
status = AS_FAILURE;
perror("toYYYYY send");
}
return status;
接收方将无误地获取第一帧发送。但是,sendto函数会在此成功发送时抛出“No such file or directory”错误。以下两个发送产生相同的错误,但sendto函数返回(-1)而不是像第一次调用中那样正确的缓冲区长度。在随后的sendto调用中,错误变为“Transort endpoint is not connected”。
接收过程复制/粘贴更复杂,但实际上它首先从套接字调用中获取文件描述符,使用recvfrom()设置地址结构,绑定和读取。
以下是一个示例输出日志,可能有用也可能没用:
remote_len: 30
local_len: 26
local: '/tmp/sockets/toYYYYY5248' remote: '/tmp/sockets/fromXXXXXXX5248'
Binding to: '/tmp/sockets/fromXXXXXXX5248'
entered selected (This is receiving function with recvfrom())
recv from '/tmp/sockets/toYYYYY5248' len: 263
Closing socket
send (successful call): Success
send: No such file or directory
send: No such file or directory
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
send: Transport endpoint is not connected
答案 0 :(得分:1)
您只在remote
时初始化out_sock == -1
。第二次调用函数remote
时会未初始化,因此会出错。