Reference no: EM132217495
Writing popen() and pclose()
The stand I/O library in C contains the functions:
FILE *popen(const char *command, const char *mode); int pclose(FILE *stream);
where "command" is the name of an executable program (normally a shell command), "mode" refers to whether the calling process will read or write to the pipe and "stream" refers to a file pointer.
The purpose of popen() is to allow a process to create another process running the program "command" which it will communicate with using an unnamed pipe.
To achieve this, the function popen() needs to execute several system calls. The diagram below gives the relationships of the processes and pipe.
| original process |>---pipe---->| new process | |that executes popen()| |running "command"|
In this assignment, you will write both the popen() and pclose() functions and use them in a program. Remember that pclose() allows the original process to be a good parent.
Your code needs to consider the following points:
The pipe() system call returns a pair of file descriptors. However, popen() return a file pointer. Use the function FILE* fdopen() to convert the file descriptor into a file pointer.
Appropriately close() the unused file descriptor in the parent and the child. The function popen() knows which to close() because of the mode parameter.
The child needs to use either dup() or dup2() to redirect standard input or standard output.
The child needs to close unneeded file descriptors before it does an exec*() (the command parameter).
The parent needs to perform all its tasks before it calls pclose(). Be careful with order of operations.