我在 c 中分叉,从子进程调用 python 程序并从父进程传递一个字符串。现在我将在我的 python 程序上打印这个字符串。我有这个代码:
void
forking ()
{
int thepipe[2];
char someString[] = "Hello, world!\n";
char readbuffer[80];
if (pipe (thepipe) < 0)
{
perror ("pipe error");
exit (EXIT_FAILURE);
}
pid_t pid = fork ();
if (pid < 0)
{
perror ("Fork failed");
}
if (pid == 0)
{
close (thepipe[1]);
execl(PYTHONPROGRAM, PYTHONPROGRAM);
exit (0);
}
else
{
close (thepipe[0]);
write (thepipe[1], someString, (strlen (someString) + 1));
wait (NULL);
}
}
如何从 python 程序中读取管道?我必须使用 os.fdopen。下面的代码不起作用。
import os,sys
r, w = os.pipe()
os.close(w)
r = os.fdopen(r)
str = r.read()
print("text =", str)
sys.exit(0)