英文:
How to: Communicate with a subprocess
问题
我有一个启动C/Lua进程的Go程序。现在我想在这两者之间进行通信。例如,在子进程(C/Lua进程)运行的中间,我想要求父进程(Go程序)进行一些计算,并等待结果。我不想使用stdin/stdout进行通信,因为这已经用于常规输出。现在我正在考虑使用套接字进行通信,但我不想重复造轮子。
-
这种通信的明显选择有哪些?
-
是否有一种(更或者更少)简单的标准方法来在Lua和Go之间传递对象?如果没有,文本块也可以。
-
Protocol Buffers适合这种情况吗?看起来有点过度设计,但我在这方面没有经验。
英文:
I have a Go program that starts a C/Lua process. Now I'd like to communicate between those two. For example, in the middle of the run of the child (the c/lua process), I'd like to ask the parent (the Go program) to do some calculations and wait for the result. I am not keen to use stdin/stdout for communication, as this is already used for regular output. Now I am thinking of using sockets for the communication, but I don't want to reinvent the wheel.
-
What are the obvious choices for this kind of communication?
-
Is there a (more or less) simple standard way to pass objects between Lua and Go? If not, text blobs would suffice.
-
Are Protocol Buffers suitable for this? Looks like overkill, but I have no experience here.
答案1
得分: 4
除了你提到的所有常见的IPC方法(是的,使用带有protobuf的Unix套接字,以及标准输入/输出),如果你在程序中运行嵌入的C/Lua代码,而不是作为一个进程启动它,你实际上可以直接在这些语言之间进行通信。
使用cgo
模块,Go代码可以调用C函数,嵌入的C代码也可以调用Go函数。请参考这里:http://golang.org/cmd/cgo/#hdr-C_references_to_Go
此外,你可以尝试一些可嵌入的Lua绑定库,用于Go,它们允许你调用Lua代码,并让你的Lua代码调用Go。请参考https://github.com/aarzilli/golua和https://github.com/stevedonovan/luar。
英文:
Besides all the usual IPC methods you've mentioned (yeah, a unix socket with protobuf should do it, and stdin/stdout as well), if you run the C/Lua code embedded in your program, and not start it as a process, you can actually communicate between the languages directly.
Using the cgo
module, Go code can call C functions, and embedded C code can call Go functions. See here: http://golang.org/cmd/cgo/#hdr-C_references_to_Go
Also, you have a couple embeddable Lua binding libraries for Go which you can try, that let you call Lua code and let your Lua code call Go. see https://github.com/aarzilli/golua and https://github.com/stevedonovan/luar/
答案2
得分: 0
我现在通过常规的TCP套接字与子进程进行通信。子进程(Lua)内置了luasocket,在Windows、Mac和Linux上似乎没有问题。
此外,我(暂时)定义了自己非常简单的协议,在最初的步骤中看起来还不错。
如果有人感兴趣的话,可以参考这个链接:https://github.com/speedata/publisher/commit/ea253382c1096274bca2d4124867c39cd0d512e5,子提交实现了TCP连接。
英文:
I now talk to the subprocess via regular tcp sockets. The child process (Lua) has luasocket built in and this seems to work on Windows, Mac and Linux without problems.
Also, I have (for now) defined my own very simple protocol which looks OK in the first steps.
Just in case anybody is interested: https://github.com/speedata/publisher/commit/ea253382c1096274bca2d4124867c39cd0d512e5 and the child commits implement the tcp connection.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论