2011-06-01 65 views
0

我想在C中可以處理請求動態內容的網絡服務器。 webserver部分已經完成。我試圖執行以下命令:調試服務器的CGI程序

http://localhost:1601/cgi-bin/test?3&7

與程序測試的代碼如下:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/wait.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <assert.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <wordexp.h> 
#define MAXLINE 300 

int main(int narg, char * arg[]) { 
    char *buf, *p; 
    char arg1[MAXLINE], arg2[MAXLINE], content[MAXLINE]; 
    int n1=0, n2=0; 

    /* Extract the two arguments */ 
    if ((buf = getenv("QUERY_STRING")) != NULL) { 
    p = strchr(buf, '&'); 
    *p = '\0'; 
    strcpy(arg1, buf); 
    strcpy(arg2, p+1); 
    n1 = atoi(arg1); 
    n2 = atoi(arg2); 
    } 

    /* Make the response body */ 
    sprintf(content, "Welcome to add.com: "); 
    sprintf(content, "%sTHE Internet addition portal.\r\n<p>", content); 
    sprintf(content, "%sThe answer is: %d + %d = %d\r\n<p>", 
     content, n1, n2, n1 + n2); 
    sprintf(content, "%sThanks for visiting!\r\n", content); 

    /* Generate the HTTP response */ 
    printf("Content-length: %d\r\n", (int)strlen(content)); 
    printf("Content-type: text/html\r\n\r\n"); 
    printf("%s", content); 
    if (fork()==0) { 
     printf("asdfagloiauergauhfgaiudfhg"); 
     execvp("ls",arg); 
     printf("child of adder error"); 
    } 
    printf("%s", content); 

    fflush(stdout); 
    exit(0); 
} 
/* $end adder */ 

它運行良好。但是,我想知道爲什麼子代碼(printf(「asdfagloiauergauhfgaiudfhg」)和execvp)沒有輸出到Web服務器的輸出中。儘管測試中的其他一切都正確輸出。

+0

哪個瀏覽器?您是否看到您發送的內容的副本,或只有一個? – 2011-06-01 04:30:31

回答

1

對於初學者,您將Content-length標頭設置爲內容的長度,然後發送內容,然後在兩個線程中發送更多數據。瀏覽器有權忽略輸出流中的內容長度字節之後的所有內容。