#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#define CGI_NAME "Get_post.ums"
#define REQUEST_METHOD "Request_method=post"
#define Request_parameter "Myname=huangzhihui"
int main (int argc, char *argv[])
{
int fd[2];
if (pipe (FD) < 0)
{
printf ("Create pipe fail.\n");
}
pid_t pid;
if ((PID = fork ()) < 0)
{
printf ("fork fail.\n");
}
else if (PID > 0)
{
* Parent * *
Simulate sending data to CGI
ssize_t length = strlen (Request_parameter);
if (write (fd[1), request_parameter, length)!= length)
{
printf ("Write error to pipe\n");
}
Close (fd[1]);
Wait for the CGI child process to read the data completely and write it.
The actual situation should be to use Select or Epoll listening
Usleep (1000);
Simulate receiving data from a CGI response
Char buff[256] = {0};
Length = Read (Fd[0], buff, sizeof (buff));
if (length <= 0)
{
printf ("Read error from pipe\n");
}
Else
{
printf ("pid%d read data=%u,%s\n", Getpid (), length, buff);
}
Close (fd[0]);
if (Waitpid (PID, NULL, 0) < 0)
{
printf ("Waitpid error\n");
}
Exit (0);
}
Else
{
* * Child * *
The input end of the redirected pipe to the standard input
if (Fd[0]!= Stdin_fileno)
{
if (Dup2 (fd[0], Stdin_fileno)!= Stdin_fileno)
{
printf ("Dup2 error to stdin");
}
Close (fd[0]);
}
The output of the redirected pipeline to standard output
if (fd[1]!= Stdout_fileno)
{
if (Dup2 (fd[1], Stdout_fileno)!= Stdout_fileno)
{
printf ("Dup2 error to stdout");
}
Close (fd[1]);
}
Overwrite process space, set CGI environment variables
Char content_length[128] = {0};
sprintf (Content_length, "content_length=%u", strlen (Request_parameter));
Char *exec_argv[3] = {request_method, content_length};
if (Execve (CGI_NAME,ARGV,EXEC_ARGV) < 0)
{
printf ("Execl error for%s", cgi_name);
}
Exit (0);
}
Exit (0);
}