C++启动一个脚本(bash,python..)并使用stdin/stdout进行datatransfare [linu
C++ start a script ( bash, python ... ) and using stdin/stdout for datatransfare [linux]
我想从我的C++代码调用python脚本。python脚本看起来像:
hello.py
#!/usr/bin/python
import sys
print "Hello!"
Readin = sys.stdin.read()
print Readin
C++代码来自堆栈溢出的另一个问题。它应该如何工作:
创建一对管道。
使用
fork()
创建子进程。孩子正在弯曲其管道到stdin/stdout。关闭另一端并启动脚本。
父亲正在听管道
read()
,接收输入。在它之后,发送消息write()
。
当进入switch (readResult = read(childToPa...
时,程序不会从父亲的行返回。
我也不知道这个写作部分是否在做它的工作。这样做是一个有前途的想法,还是有其他工作的可能性?感谢!
它看起来像:
// maybe not all includes are necessary
#include <iostream>
#include <fstream>
#include <string>
#include <errno.h>
#include <sys/stat.h> // mkdir
#include <stdlib.h> // system()
#include <unistd.h> // rmdir
#include <cstring> // memset
// wait:
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main() {
char target[] = "./hello.py";
enum PIPE_FILE_DESCRIPTERS {
READ_FD = 0, WRITE_FD = 1
};
enum CONSTANTS {
BUFFER_SIZE = 100
};
int parentToChild[2];
int childToParent[2];
pid_t pid;
string dataReadFromChild;
char buffer[BUFFER_SIZE + 1];
memset(buffer,0x00,BUFFER_SIZE + 1);
ssize_t readResult;
int status;
int retPipe1 = pipe(parentToChild);
int retPipe2 = pipe(childToParent);
switch (pid = fork()) {
case -1:
printf("Fork failed");
exit(-1);
case 0: /* Child will start scripts*/
{
// Bending stdin/out to the pipes?
int retdup21 = dup2(parentToChild[READ_FD], STDIN_FILENO);
int retdup22 = dup2(childToParent[WRITE_FD], STDOUT_FILENO);
int retdup23 = dup2(childToParent[WRITE_FD], STDERR_FILENO);
// Close in this Process the other sides of the pipe
int retclose1 = close(parentToChild[WRITE_FD]);
int retclose2 = close(childToParent[READ_FD]);
int retexe = execlp( target ," "); // warning not enough variable arguments to fit a sentinel [-Wformat=]
printf("This line should never be reached!!!"); // why? what happens if execlp finishes?
exit(-1);
break; // to make the compiler happy =)
}
default: /* Parent */
cout << "Child " << pid << " process running..." << endl;
// close the other ends of the pipe from the other process.
int retdup21 = close(parentToChild[READ_FD]);
int retdup22 = close(childToParent[WRITE_FD]);
// readtry
while (true) {
switch (readResult = read(childToParent[READ_FD], buffer, 1)) // execution does not return from this function.
{
case 0: /* End-of-File, or non-blocking read. */
{
cout << "End of file reached..." << endl << "Data received was (" << dataReadFromChild.size() << "):" << endl
<< dataReadFromChild << endl;
cout << "starting writing" << endl;
char bufferW[] = "{"AElement":"Something"} ";
int writeResult = write(parentToChild[WRITE_FD],bufferW,sizeof(bufferW));
int saveerrno = errno;
if( -1 == writeResult)
{
cout << "errno while writing: " << errno << std::endl;
if ( 9 == saveerrno )
cout << "Errno Bad File descriptor" << endl;
}
cout << "Write Result: " << writeResult << std::endl;
int retWait = waitpid(pid, &status, 0);
cout << endl << "Child exit staus is: " << WEXITSTATUS(status) << endl << endl;
exit(0);
}
case -1:
{
if ((errno == EINTR) || (errno == EAGAIN)) {
errno = 0;
break;
} else {
printf("read() failed");
exit(-1);
}
}
default:
dataReadFromChild.append(buffer, readResult);
printf("%s",buffer);
memset(buffer,0x00,BUFFER_SIZE + 1);
break;
}
} /* while ( true ) */
} /* switch ( pid = fork() )*/
}
您的问题是缓冲输出、未关闭的文件描述符以及使用 EOF 发出传输部分结束的信号。前两个问题可以解决,但最后一个问题需要不同的方法。稍后会详细介绍。
循序渐进:
Python正在使用缓冲 I/O,因此您可能希望在第一个 print 语句后添加行sys.stdout.flush()
来强制 Python 刷新输出。现在"Hello!n"
是逐个字符阅读的。
但接下来的read
块,直到新角色到达或管道关闭。Python脚本的STDOUT仍然打开,C++程序正在等待一些东西到达,但Python脚本本身也在等待一些输入。经典的僵局。
您可能会丢弃 python 脚本中的最后一次打印并尝试关闭其 STDOUT。由于read
块直到引用管道写入端的所有文件描述符都关闭,因此您必须在flush
之后添加os.close(sys.stdout.fileno())
和os.close(sys.stdout.fileno())
。
但是仍然有有效的文件描述符引用该管道的写入部分。还记得C++源中的dup2
吗?在这三行dup2
之后,仍然有parentToChild[READ_FD]
和childToParent[WRITE_FD]
引用脚本STDIN和STDOUT。所以我们必须关闭它们。在dup2
后立即添加close(parentToChild[READ_FD]);
和close(childToParent[WRITE_FD]);
。现在read
当 Python 脚本关闭 STDOUT 和 STDERR 时返回0
。
接下来,父级发送"{"AElement":"Something"} "
并到达waitpid
当子级退出时返回。但是孩子仍然在阅读STDIN。所以你必须在waitpid
之前添加close(parentToChild[WRITE_FD]);
.
现在是概念部分:在它返回0
(管道关闭(之前,您无法read()
,然后继续从该关闭的管道读取。您的选择:
- 读取一次,直到管道关闭。没有第二条消息。
- 知道要读多少。提前或通过解释收到的字节。
- 监控两个管道,例如使用 poll(2( 并动态决定是要读取还是写入。
顺便说一句:execlp
的参数是const char *file, const char *arg, ...
的,其中arg, ...
是通常的char *args[]
,以arg[0]
(!(开头并以空指针结尾。请将该行更改为int retexe = execlp(target, target, (char*) NULL);
#!/usr/bin/python2.7
import os
import sys
print "Hello!"
sys.stdout.flush()
os.close(sys.stdout.fileno())
os.close(sys.stderr.fileno())
data = sys.stdin.read()
with open("data_received_by_child.txt", "w") as fp:
print >>fp, data
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int main()
{
const char *target = "./hello.py";
enum PIPE_FILE_DESCRIPTERS {
READ_FD = 0, WRITE_FD = 1
};
/* Make pipes */
int parentToChild[2]; /* Parent to child pipe */
if (pipe(parentToChild) < 0)
{
perror("Can't make pipe");
exit(1);
}
int childToParent[2]; /* Child to parent pipe */
if (pipe(childToParent) < 0)
{
perror("Can't make pipe");
exit(1);
}
/* Create a child to run command. */
pid_t pid = fork();
switch (pid)
{
case -1:
perror("Can't fork");
exit(1);
case 0: /* Child */
close(parentToChild[WRITE_FD]);
close(childToParent[READ_FD]);
dup2(parentToChild[READ_FD], STDIN_FILENO);
dup2(childToParent[WRITE_FD], STDOUT_FILENO);
close(parentToChild[READ_FD]);
close(childToParent[WRITE_FD]);
execlp(target, target, (char *) NULL);
perror("Can't execute target");
exit(1);
default: /* Parent */
close(parentToChild[READ_FD]);
close(childToParent[WRITE_FD]);
cout << "Child " << pid << " process running..." << endl;
}
/* Read data from child */
string dataReadFromChild;
char ch;
int rc;
while ((rc = read(childToParent[READ_FD], &ch, 1)) != 0)
{
if (rc == -1) {
if ((errno == EINTR) || (errno == EAGAIN)) {
continue;
}
perror("read() failed");
exit(-1);
}
dataReadFromChild += ch;
}
close(childToParent[READ_FD]);
cout << "End of file reached..." << endl;
cout << "Data received was (" << dataReadFromChild.size() << "):" << endl;
cout << dataReadFromChild << endl;
/* Write data to child */
cout << "starting writing" << endl;
const char bufferW[] = "{"AElement":"Something"} ";
while (true) {
int rc = write(parentToChild[WRITE_FD], bufferW, sizeof(bufferW));
if (rc == -1) {
if ((errno == EINTR) || (errno == EAGAIN)) {
continue;
}
perror("write() failed");
exit(-1);
}
break;
}
close(parentToChild[WRITE_FD]);
/* Wait for child to exit */
int status;
int retWait = waitpid(pid, &status, 0);
cout << endl << "Child exit status is: " << WEXITSTATUS(status) << endl << endl;
}
- 当使用带有stdin和stdout重定向的双进程管道时,如何避免stdin上的重复输入
- stdin,stdout,stderr是如何关闭的
- 通过stdin/stdout和qdatastream与Qprocess进行通信
- QT控制台:记录所有stdin和stdout要文件
- 将Stdout重定向到另一个程序的Stdin
- 为什么 read() 在管道连接到使用 boost::asio for STDIN/STDOUT 的程序时,使用 EAG
- 从C/C++调用Objective C stdin/stdout管道时,它是如何工作的
- stdout and stdin relationships
- 在c++中重定向bash stdin和stdout
- C++Eclipse:stdin位于与stdout不同的控制台中
- C++启动一个脚本(bash,python..)并使用stdin/stdout进行datatransfare [linu
- 测试使用 tty stdin 和 stdout 的程序
- C/C++服务器,通过stdin/stdout与客户端通信(阻塞stdin,直到读取了大量字节)
- 如何正确启动进程并转发 stdin/stdout/stderr
- 如何在c++中运行应用程序,并在windows中向其stdin写入和从其stdout读取
- 仅重定向子进程stdin,并从stdout和stderr中删除数据
- 如何用Qt 5.7初始化stdout stdin
- StdIn / StdOut / StdErr重定向到WinSock连接
- NodeJS-C/C++插件通信(stdin-stdout)
- 重定向标准I/O: freopen + stdin/stdout vs open + dup2