How to redirect stdout of the ls -l
We must shed more light on the processes (parent and children) involved into this code. How many processes your program creates during its run? The correct answer is - three. Two processes are the parent and the explicitly forked child. The third one is created by the system("ls -l") call. This function implicitly forks another process that executes (by calling an exec family function) the "ls -l" sell command. What you need to redirect is the output of the child process created by the system() function. It is sad, but the system() does not establish IPC between the participators. If you need to manipulate with the output, do not use system().
I agree with @leeduhem, popen() could be the best approach. It works exactly as the system(), i.e. forks a new process and executes "ls -l". In addition, it also establishes a pipe IPC between the participators, so it is easy to catch the child output and to do with it whatever you want:
char buff[1024];
FILE *fd;
// instead of system("ls -l")
fd = popen("ls -l", "r");
// check for errors
while(fgets(buff, sizeof(buff), fd) != NULL)
{
// write to the shared memory
}
pclose(fd);
If you do not want to use the popen() function, you may write a similar one. The general approach is
- open a pipe()
- fork() a new process
- redirect stdout using dup2
- call a suitable exec() function (probably execl()) executing "ls -l"
- read from the descriptor you are duplicating by dup2.