Я добавил решение с потоком из jcollado
в мой модуль Python easyprocess .
Установка:
pip install easyprocess
Пример:
from easyprocess import Proc
# shell is not supported!
stdout=Proc('ping localhost').call(timeout=1.5).stdout
print stdout
Используйте popen
функция.
Пример (не завершенный, производственный качественный код, никакая обработка ошибок):
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
Пример:
#include <stdio.h>
int main() {
FILE * f = popen( "ls -al", "r" );
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return 1;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
fprintf( stdout, "%s", buf );
}
pclose( f );
}
popen
определенно делает задание, которое Вы ищете, но оно имеет несколько недостатков:
, Если Вы хотите, вызывают подпроцесс и обеспечивают вход и получают вывод тогда, необходимо будет сделать что-то вроде этого:
int Input[2], Output[2];
pipe( Input );
pipe( Output );
if( fork() )
{
// We're in the parent here.
// Close the reading end of the input pipe.
close( Input[ 0 ] );
// Close the writing end of the output pipe
close( Output[ 1 ] );
// Here we can interact with the subprocess. Write to the subprocesses stdin via Input[ 1 ], and read from the subprocesses stdout via Output[ 0 ].
...
}
else
{ // We're in the child here.
close( Input[ 1 ] );
dup2( Input[ 0 ], STDIN_FILENO );
close( Output[ 0 ] );
dup2( Output[ 1 ], STDOUT_FILENO );
execlp( "ls", "-la", NULL );
}
, Конечно, можно заменить execlp
любой из других исполнительных функций как соответствующие.