Two------Web services and CGI interactive data with CGI principle parsing

Source: Internet
Author: User
Tags strlen web services

#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);

}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.