c语言与python通信_C和Python – 与套接字通信
我正在嘗試使用UNIX域套接字在C程序和
Python腳本之間進行通信. Python腳本通過UNIX域套接字將數據發送到C程序.
這是我的C程序的相關代碼:
#include
#include
#include
#include
#include
#include
#define UNIX_PATH_MAX 100
int main(void)
{
struct sockaddr_un address;
int socket_fd,connection_fd;
socklen_t address_length;
pid_t child;
socket_fd = socket(AF_UNIX,SOCK_STREAM,0);
if (socket_fd < 0){
printf("socket() failed\n");
return 1;
}
unlink("/tmp/demo_socket");
memset(&address,sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path,UNIX_PATH_MAX,"/tmp/demo_socket");
if (bind(socket_fd,(struct sockaddr *) &address,sizeof(struct sockaddr_un)) != 0) {
printf("bind() failed\n");
return 1;
}
if(listen(socket_fd,5) != 0) {
printf("listen() failed\n");
return 1;
}
//----------------WHILE LOOP----------------------->
while((connection_fd = accept(socket_fd,&address_length)) > -1)
{
.
.
.(doesn't get any further than this)
這是我用來向套接字發送消息的python腳本:
import socket
s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
s.connect("/tmp/demo_socket")
print "Sending..."
s.send("Hello world")
x = s.recv(1024)
print x
s.close()
python腳本失敗,錯誤“Broken Pipe”. C程序永遠不會進入while循環,因為accept()函數失敗并返回’-1′.
為什么accept()失敗了?我能做些什么才能讓它成功?
總結
以上是生活随笔為你收集整理的c语言与python通信_C和Python – 与套接字通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python数据校验_最近抽空造了一个数
- 下一篇: python使用spark-sql读取数