Popen
Linux C
Process I/O functions, used with the Pclose function.
Table header File
#include <stdio.h>
function definition
FILE * Popen (const char * command, const char * type);
int Pclose (FILE * stream);
Function description
The Popen () function, by creating a pipe, invokes fork to produce a subprocess, executing a shell to run a command to open a process. This process must be closed by the pclose () function, not the fclose () function. The Pclose () function closes the standard I/O stream, waits for the command to finish, and then returns the shell's termination state. If the shell cannot be executed, then Pclose () returns the same termination status as the shell has executed.
The type parameter can only be read or write, and the resulting return value (standard I/O stream) also has a read-only or write-only type corresponding to type. If type is "R", the file pointer is connected to the standard output of the command, and if type is "W" the file pointer is connected to the standard input of the command.
The command argument is a pointer to a NULL-terminated shell command string. This line of command will be uploaded to Bin/sh and using the-c flag, the shell will execute this command.
The Popen return value is a standard I/O stream that must be terminated by Pclose. As mentioned earlier, this flow is one-way. So writing to this stream is equivalent to writing the standard input to the command, and the standard output of the command is the same as the process calling Popen. In contrast, reading data from a stream is equivalent to reading a command's standard output; the standard input for a command is the same as the process that invokes Popen.
return value
If the call to fork () or pipe () fails, or the inability to allocate memory returns NULL, the standard I/O stream is returned.
return error
Popen did not set the errno value for memory allocation failure.
If an error occurs when calling fork () or pipe (), errno is set to the appropriate error type.
If the type argument is not valid, errno returns EINVAL.
Use examples
if ((Fp=popen ("/usr/bin/uptime", "R")) ==null);
{
sprintf (buf, "Error:%s\n", Strerror (errno));
...//exception handling
}
Else
{
....
Pclose (FP);
}