2016-11-14 35 views
-2

我必须将用C编写的程序与Python中的其他程序(Linux os)连接起来。第一个应该每隔几秒发送一个特定的字符串,并且必须由Python程序接收以完成一些任务。将字符串从C发送到Python程序

任何建议或示例?

问候 马克西

+0

这个问题很模糊,很难理解,一般混乱。 –

+0

你能提供一个[MCVE](http://stackoverflow.com/help/mcve)吗? –

+0

这是什么操作系统? – Matt

回答

0

这里的一个C程序(send_string.c)输出字符串 “Hello”:即从standard input接收的字符串,并且执行

#include <stdio.h> 

int main() 
{ 
    printf("Hello"); 
    return 0; 
} 

这里的一个Python程序(receive_string.py)任务(在这种情况下,它打印出字符串):

import sys 

input = sys.stdin.read() 
print input 

一旦你编译C程序中,可以使用Linux的连接方案pipeline

./send_string | python receive_string.py 

如果您希望重复这样做,说每5秒,可以使用whilesleep命令:

while true; do ./send_string | python receive_string.py; sleep 5; done 

要停止循环,请按Ctrl + C。如果知道执行循环的次数,则可以使用for循环代替。

0

在这里,我发现从here

它使用zeromq库使用客户端 - 服务器结构修改一个不错的选择。 Zeromq在任何平台上以任何语言连接您的代码,并通过inproc,IPC,TCP,TIPC,多播和其他方式传输消息。

这里的服务器:

/* original Time Server - Modified: zeromq_1.c 
Author - Samitha Ransara 
www.mycola.info 

Comp: gcc -Wall -g zeromq_1.c -lzmq -o zeromq_1 
*/ 


#include <zmq.h> 
#include <stdio.h> 
#include <time.h> 
#include <unistd.h> 
#include <assert.h> 


int main (void) 
{ 
    printf ("Sockets initializing\r\n"); 
    // Socket to talk to clients 
    void *context = zmq_ctx_new(); 
    void *responder = zmq_socket (context, ZMQ_REP); 
    int rc = zmq_bind (responder, "tcp://127.0.0.1:5555"); 
    assert (rc == 0); 

    char tmpbuf[128]; 
    char buffer [10]; 
    int i=0; 


    while(i<6) 
    { 

     snprintf(tmpbuf, sizeof(tmpbuf), "Mensaje Nro %i\n",i); 
     zmq_recv (responder, buffer, 10, 0); 
     printf ("Request Recieved\r\n"); 

     //zmq_send (responder, tmpbuf, 8, 0); 
     zmq_send (responder, tmpbuf, 16, 0); 
     printf ("Responded with %s\r\n",tmpbuf); 
     i++; 
    } 
    return 0; 
} 

在这里,Python客户端:

# PYzeromq_1.py 
# 

from __future__ import print_function 
import zmq,time,sys 



def main(): 

    print("Connecting to Data Service…") 
    sys.stdout.flush() 
    context = zmq.Context() 

    # Socket to talk to server 
    socket = context.socket(zmq.REQ) 
    socket.connect("tcp://127.0.0.1:5555") 
    print("Connected....") 

    while(True): 

     #print("\r\nSending request …") 
     socket.send("Requesting... ") 

     # Get the reply. 
     message = socket.recv() 

     #print("Time %s" % message, end='\r') 
     print(message) 
     time.sleep(1) 

    return 0 

if __name__ == '__main__': 
    main()