所以我试图通过父级创建的管道将我的C父进程中的字符串发送到我的python子进程。之后,我想从我的python子项中将一个字符串发送回父级并在那里打印出来。
这是我的C代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char **argv, char **envp) {
pid_t childpid;
int status;
int test;
char *argument;
int fd[2];
char *numbers = "3,5,7\n";
argument = "./fork.py";
char *python[] = {argument, NULL};
test = 0;
pipe(fd); //Create pipe
childpid = fork();
if (childpid==(-1) ) {
perror( "fork" );
return -1;
} else if (childpid==0) {
//in child
execvp(argument, python);
}
//in parent
write(fd[1], numbers, sizeof(numbers));
close(fd[1]);
waitpid(-1, &status, 0); //Wait for childprocess to finish
char buffer[1024];
while (read(fd[0], buffer, sizeof(buffer)) != 0) {} //Read pipe to buffer
if (test < 0) { //If failed print error message or success message
printf("Error: %s\n", buffer);
} else {
printf("%s\n", buffer);
}
return 0;
}
这是我的Python代码(fork.py):
#!/usr/bin/env python3
import os
import sys
def main():
r, w = os.pipe()
os.read(r, 12)
os.close(r)
os.write(w, "This is a test")
os.close(w)
sys.exit(0)
if __name__ == '__main__':
main()
我做错了什么,因为管道应该分叉,因此孩子可以使用?似乎没有数据传递给管道或python进程无法以某种方式访问管道来检索数据。是的,它必须是一个管道。
答案 0 :(得分:1)
您正在python中生成一对新的管道句柄。您必须使用在C中创建的相同句柄。
创建一对用于从C到python的通信,另一对用于从Python到C的通信:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char **argv, char **envp) {
pid_t childpid;
int status;
int test;
int fd_a[2], fd_b[2];
char *numbers = "3,5,7\n";
test = 0;
pipe(fd_a); //Create pipe
pipe(fd_b);
childpid = fork();
if (childpid==(-1) ) {
perror( "fork" );
return -1;
} else if (childpid==0) {
//in child
char *argument = "./fork.py";
char fd0[20], fd1[20];
snprintf(fd0, 20, "%d", fd_a[0]);
snprintf(fd1, 20, "%d", fd_b[1]);
close(fd_a[1]);
close(fd_b[0]);
char *python[] = {argument, fd0, fd1, NULL};
execvp(argument, python);
}
close(fd_a[0]);
close(fd_b[1]);
//in parent
write(fd_a[1], numbers, sizeof(numbers));
close(fd_a[1]);
waitpid(-1, &status, 0); //Wait for childprocess to finish
char buffer[1024];
while (read(fd_b[0], buffer, sizeof(buffer)) != 0) {} //Read pipe to buffer
if (test < 0) { //If failed print error message or success message
printf("Error: %s\n", buffer);
} else {
printf("%s\n", buffer);
}
return 0;
}
在python中获取参数并将它们用作句柄:
#!/usr/bin/env python3
import os
import sys
def main():
r, w = map(int, sys.argv[1:])
os.read(r, 12)
os.close(r)
os.write(w, b"This is a test")
os.close(w)
sys.exit(0)
if __name__ == '__main__':
main()