简体   繁体   中英

writing cgi code by C language

Is this possible to write CGI code by C or C++ ? please give me a "hello World !!!" Example .

Absolutely.

#include <stdio.h>

int main(int argc, char *argv[]])
{
  printf("Content-type: text/plain\n\n");
  printf("Hello, world!\n")
}

Eva, once you understand the basics of Ignacio's answer (cgi-bin, executing from browser, web server, etc) there are some very helpful libraries to assist with web type execution.

Here is the library I used for my cgi in C, works great, saves you days:
(cgihtml is a set of CGI and HTML routines written for C)
http://eekim.com/software/cgihtml/index.html

you can add html templates for displaying large amounts of data:
http://www.algonet.se/~thunberg/template2doc/

Light weight WebServers:
http://en.wikipedia.org/wiki/Comparison_of_lightweight_web_servers

and more resources:
http://cgi.resourceindex.com/Programs_and_Scripts/C_and_C++/Libraries_and_Classes/

http://en.wikipedia.org/wiki/Common_Gateway_Interface

Have a look at kcgi

kcgi is an open source CGI and FastCGI library for C web applications. It is minimal, secure, and auditable

#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */
#include <stdlib.h> /* EXIT_SUCCESS, etc. */
#include <kcgi.h>

int main(void) {
  struct kreq r;
  const char *page = "index";
  if (KCGI_OK != khttp_parse(&r, NULL, 0, &page, 1, 0))
    return(EXIT_FAILURE);
  khttp_head(&r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
  khttp_head(&r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME__MAX == r.mime ? 
      KMIME_APP_OCTET_STREAM : r.mime]);
  khttp_body(&r);
  khttp_puts(&r, "Hello, world!");
  khttp_free(&r);
  return(EXIT_SUCCESS);
}

Compile this simple source code into an executable file:

#include <stdio.h>

int main()
{
    printf("content-type: text/plain\n\n");
    printf("Hello, world!");

    return 0;
}

I assume that the compiled file is cgi-app.cgi :

gcc cgi-src.c -o cgi-app.cgi

If you run httpd as your server software, you can put cgi-app.cgi into your directories:

  1. cgi-bin : it is allowed to run CGI in most of cases.
  2. htdocs : add 2 lines into your .htaccess file:
 
 
Options +ExecCGI AddHandler cgi-script .cgi

Never forget set suitable execute permission for your .htaccess and cgi-app.cgi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM