I'm currently programming on an Aldebaran's NAO and I need to execute a shell command from the C++ code, and then get back the output in a buffer. I used the classical method of fork, execve and pipe, but, precisely when I test it in a NAO Module, the pipe doesn't work. I mean, there is no output from the command written in the terminal, but my read() in the parent process waits on STDIN.
What is really strange is that if I just do a simple program to test forks and pipes, with exactly the same command executed, the pipe works.
What is even more strange is that the write(1, "HERE\n", 5) is properly executed and the message is catched back by the read();
My conclusion at this point is that, in a C++ NAO Module, the dup2() works in the child process, but not on the parent one.
Do you guys have any idea of what may be the matter ?
Here is the code :
void
Sonar::getResult()
{
int pfd[2];
char buf[4] = { 0, 0, 0, 0 };
char *arg[] = { "/home/nao/picocom", "-b", "9600", "dev/ttyUSB0", 0 };
int pid = 0;
pipe(pfd);
if ((pid = fork()) == 0)
{
close(pfd[0]);
dup2(pfd[1], 1);
write(1, "HERE\n", 5);
int ret = execve(arg[0], arg, 0);
if (ret == -1)
{
close(pfd[1]);
write(1, "Fail.\n", 6);
kill(getpid(), 15);
}
}
std::cout << "Pid : " << pid << std::endl;
close(pfd[1]);
dup2(pfd[0], 0);
waitpid(pid, 0, 0);
int r = read(0, buf, 3);
close(pfd[0]);
std::cout << "Read : " << r << std::endl;
printResult(buf);
}