Before discussing the implementation of RunCommand , consider this piece of code:
string psOutput = RunCommand("ps -elf",""); string grepOutput = RunCommand("grep somequerytext", psOutput);
In the above code snippet, the problem is that the commands are run sequentially and not run in parallel / parallel. (See Programming with POSIX Streams p. 9 ) For an example, if ps -elf generates a huge amount of data that will be stored in psOutput and then passed to the next command. But in a real implementation, each process in a pipe starts at the same time, and the data is transmitted using pipe (with some buffering, of course), and there is no need to wait for one process to complete before another process starts.
I suggest you study Richard Stephen’s Advanced Programming in the Unix Environment chapter. "Process Control" p. 223 to implement the system . Based on Richard Steven's code, a sample RunCommand implementation will look like this (skeletal code only, without error checking):
int RunCommand(string command) { pit_t pid; if ( ( pid = fork() ) < 0 ) return -1; else if (pid == 0) { execl("/bin/sh", "sh", "-c", command.c_str(), (char*) 0); } else { wait(pid, ...); } }
and then the following functions are called:
string s("ps -elf | grep somequerytext"); int status = RunCommand(s);
The shell will take care of parsing its input and running commands by installing a pipe between them. If you're interested in understanding how the shell works, see the “Minishell Example” in Terrence Chan Unix system programming using C ++ chap.8 “Unix Processes” (Jonathan Leffler answer pretty much describes the shell implementation!)
source share