写一个嵌入式的进程间的socket通信接口
时间: 2023-07-14 15:12:20 浏览: 49
嵌入式系统中的进程间通信可以使用Socket进行实现。下面是一个简单的嵌入式的进程间Socket通信接口的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCK_PATH "/tmp/mysocket"
int main(void)
{
int s, t, len;
struct sockaddr_un remote;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("Trying to connect...\n");
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
printf("Connected.\n");
while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
if (send(s, str, strlen(str), 0) == -1) {
perror("send");
exit(1);
}
if ((t=recv(s, str, 100, 0)) > 0) {
str[t] = '\0';
printf("echo> %s", str);
} else {
if (t < 0) perror("recv");
else printf("Server closed connection\n");
exit(1);
}
}
close(s);
return 0;
}
```
这个例子中,使用了UNIX domain socket,创建了一个socket连接,并通过send()和recv()函数来进行数据的传输。在这个例子中,客户端通过输入信息发送给服务端,并接收服务端的响应信息。