【发布时间】:2015-05-14 16:03:43
【问题描述】:
有没有办法在连续运行的 C 程序和连续运行的 Python 程序之间传递数据? C 程序首先启动很重要。
到目前为止,我有(对于 C 端):
void run_cmd(char *cmd[])
{
int parentID = getpid();
char str[1*sizeof(double)];
sprintf(str, "%d", parentID);
char* name_with_extension;
name_with_extension = malloc(2+strlen(cmd[1])+1*sizeof(int)+1);
strcat(name_with_extension, cmd[1]);
strcat(name_with_extension, " ");
strcat(name_with_extension, str);
pid_t pid;
char *argv[] = {"sh", "-c", name_with_extension, NULL};
int status;
//printf("Run command: %s\n", cmd);
status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ);
if (status == 0) {
//printf("Child pid: %i\n", pid);
//printf("My process ID : %d\n", getpid());
//if (waitpid(pid, &status, 0) != -1) {
// printf("Child exited with status %i\n", status);
//} else {
// perror("waitpid");
//}
//part below is not tested and will probably not work
int myout[2];
pipe(myout);
int status;
int ch;
do {
if (read(myout[0], &ch, 1)>0){
write(1, &ch, 1);
}
waitpid(pid, &status, WNOHANG);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
对于 Python,我现在只能使用以下方法获取参数列表:
print 'Arguments ', str(sys.argv)
据我了解,subprocess.Popen 不是一个可行的方法,因为它会创建一个我不想要的新进程。
在 Python 中嵌入(或反向)C 不是一种选择,因为代码太大。
我认为使用进程 IDs 和可能的 sockets 之间的通信数据,但不确定并需要一些建议.
目标是在 Windows 中实现这一点,但统一的单一实现会更好。
【问题讨论】:
-
您的代码中有 未定义的行为,
malloc函数不会初始化它分配的内存,因此当您调用strcat时,它会查找字符串终止符可能不在分配的内存中,您可能会超出分配的内存范围。 -
@JoachimPileborg 该代码仅用于测试。如果重要,程序运行如下:./c_prog ./py_prog,其中py_prog在启动时接收父端口号
-
@MocialovBoris 修复你已经知道错误的地方,(因为 Joachim 发布的内容),否则它可能会搞砸你未来的调试。至于“有没有办法在连续运行的C程序和连续运行的Python程序之间传递数据?”,那么当然有。
-
@MartinJames 哦,我错过了这样的答案
-
另一个选项是基于文件系统的 FIFO 队列。
标签: python c interprocess inter-process-communicat