Hello,
Thank you for the answers.
So, now I'm sure it's not something "impossible" that I'm trying to do.
But I'm not there yet. I've copied what I've got so far below.
With this piece of code, I can send ftp commands and get the response on standard output. But how do I catch it now ?
I thought read(fd[0],receive,strlen(receive)); would do this.
Maybe something is wrong with the close and dup'ing in the child process ?
I haven't tried the popen yet, because I have the idea that I'm very close with what I have now.
Does anyone see what's still wrong ?
int fd[2], nStatus;
pid_t pid;
pipe\(&fd[0]\); //create pipe
if \(\(pid=fork\(\)\) != 0\) \{
// parent
close\(fd[0]\);
//close\(STD_OUTPUT\);
//dup\(fd[1]\); // sets stdout to this pipe end
//close\(fd[1]\); // don't need fd anymore
std::cout << "I'm the parent. I'm a child process of : " << getppid\(\) << ", my pid is " << getpid\(\) << std::endl;
\} else \{
// child
close\(fd[1]\);
close\(STD_INPUT\);
dup\(fd[0]\); // replace stdin
close\(fd[0]\);
std::cout << "I'm the child. I'm a child process of : " << getppid\(\) << ", my pid is " << getpid\(\) << std::endl;
std::string szStartCmd = "ftp -i -n -v 192.168.149.31";
int nExecRes = execl\("/bin/sh", "sh", "-c", szStartCmd.c_str\(\), \(char *\)0\);
\}
sleep\(1\);
std::cout << "I'm a child process of : " << getppid\(\) << ", my pid is " << getpid\(\) << std::endl;
// Wait for the child process to end, but without blocking !
// If the child process exits immediately, we assume ftp couldn't be started -> return false
// else the child process is waited for later \(it becomes a "zombie" process when ftp is closed,
// by calling waitpid, the zombie processes are cleared.
int nChildDied = waitpid\(pid, &nStatus, WNOHANG\);
if \(nChildDied == 0\)
\{
// Child is not dead -> protocol analyser was started OK
std::cout << "ftp started, child not dead" << std::endl;
\}
else if \(nChildDied > 0\)
\{
// A child process died -> error starting protocol analyser
if \(WIFEXITED\(nStatus\)\)
\{
std::cout << "child process with pid = " << nChildDied << " died. Child WIFEXITED status = "
<< nChildDied << WEXITSTATUS\(nStatus\);
\}
if \(WIFSIGNALED\(nStatus\)\)
\{
std::cout << "child process with pid = " << nChildDied << "died. Child WIFSIGNALED status = "
<< nChildDied << WTERMSIG\(nStatus\);
\}
std::cout << "error starting ftp";
\}
else if \(nChildDied < 0\)
\{
// An error occured
if \(errno == ECHILD\)
\{
std::cout << "no child process exists";
\}
else if \(errno == EINTR\)
\{
std::cout << "calling process interrupted by a signal";
\}
else if \(errno == EINVAL\)
\{
std::cout << "bad argument passed to waitpid";
\}
\}
char send[80], receive[80] = "initial value";
fprintf\(stdout, "Ftp Command ? > "\); fgets\(send, 80, stdin\);
write\(fd[1],send,strlen\(send\)\);
read\(fd[0],receive,strlen\(receive\)\);
std::cout << "response from ftp : " << receive << std::endl;
fprintf\(stdout, "Ftp Command ? > "\); fgets\(send, 80, stdin\);
write\(fd[1],send,strlen\(send\)\);
...