popen
sicuramente fa il lavoro che stai cercando, ma ha alcuni inconvenienti:
- Si invoca una shell sul comando si sta eseguendo (il che significa che è necessario untaint eventuali stringhe di comando utente fornita)
- funziona solo in una direzione, o si può fornire un contributo al sottoprocesso o può leggere la sua uscita.
Se si vuole richiamare un sottoprocesso e fornire input e catturare l'uscita poi si dovrà fare qualcosa di simile:
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);
}
Naturalmente, è possibile sostituire il execlp
con uno qualsiasi degli altri exec funzioni come appropriato.
fonte
2009-03-23 02:03:11
vedere il collegamento @ Mehrdad, ha un esempio con ls =) – bayda