我是 socketpairs 的新手,我需要我的每个 child 将信息从结构传递给父级。有人告诉我这可以使用 SOCK_DGRAM 完成,但我不知道该怎么做。我查看了互联网但我找不到一个具体的例子。你能举个例子吗,你能把一个由 2 个整数和一个字符串组成的结构传递给父级吗?我只想要一个例子,这样我就可以理解我如何构建这种socketpair 并通过它发送信息。谢谢
最佳答案
以下情况如何:
int sockets[2];
if (socketpair(AF_INET, SOCK_DGRAM, 0, sockets) != -1)
{
int res = fork();
if (res == 0)
{
/* In child process */
/* We only need one socket, so close the other */
close(sockets[0]);
struct some_structure my_struct;
write(sockets[1], &my_struct, sizeof(my_struct));
/* All done */
exit(0);
}
else if (res > 0)
{
/* In parent process */
/* We only need one socket, so close the other */
close(sockets[1]);
struct some_structure my_struct;
read(sockets[0], &my_struct, sizeof(my_struct));
}
}
以上代码不检查或处理错误。它不能处理包含指针的结构,但使用数组的结构没问题。
关于c - linux fork socketpair sock_dgram,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14212377/