CGI原理解析之二------WEB服務和CGI互動資料

來源:互聯網
上載者:User

標籤:linux   c   web服務   cgi   重新導向   


#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 */                
        //類比先 CGI 傳送資料
        ssize_t length = strlen(REQUEST_PARAMETER);
        if (write(fd[1], REQUEST_PARAMETER, length) != length)
        {
            printf("write error to pipe\n");
        }
        close(fd[1]);
        
        //等待CGI子進程完全把資料讀取後寫入,
        //實際情況應該是使用select 或者 epoll 監聽
        usleep(1000);

        //類比接收 CGI 應答的資料        
        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 */
        //重新導向標準輸入到管道的輸入端
        if (fd[0] != STDIN_FILENO)
        {
            if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO)
            {
                printf("dup2 error to stdin");
            }
            close(fd[0]);
        }

        //重新導向標準輸出到管道的輸出端
        
        if (fd[1] != STDOUT_FILENO)
        {
            if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
            {
                printf("dup2 error to stdout");
            }
            close(fd[1]);
        }

        //覆蓋進程空間,設定CGI環境變數
        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);

}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.