GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 12-Sep-2009, 07:57
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 845
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

How to "get" environment variables


Hi , this is probably dumb but I can't think of anything and you guys are hungry! so
How can I get a value from my shell into my program?
CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  char buff[256]= {0};

  printf("Print SHELL and env_var: \n");

  system("echo $SHELL");
  system("echo $env_var");

  sprintf(buff, "%s", (char*)(system("echo $env_var"))  );

  printf("buff= <");  /* should print if we get past sprintf() */
  fflush(stdout);

  printf("%s> \n", buff);

  return 0;
}

/*
gcc -Wall -W -pedantic environment_var.c -o environment_var

#### Set the variable in the shell:

>  export env_var="Now is the time for all good men..."

>  echo $env_var
Now is the time for all good men...

#### 
>  sh 

sh-3.1$ echo $env_var
Now is the time for all good men... 

sh-3.1$ exit
>  

#### trial run:

>  ./environment_var
Print SHELL and env_var: 
/bin/bash
Now is the time for all good men...
Now is the time for all good men...
Segmentation fault
*/
Code:
> ./environment_var Print SHELL and env_var: /bin/bash Now is the time for all good men... Now is the time for all good men... Segmentation fault
system() just executes the command and returns status, no pointer or anything.
I guess system("echo blah"); goes to stdout.
Should I try to "catch" that?
or would I need to pipe data or something like that?
Ultimately I am trying to handle simple html <form method='get' action='../cgi-bin/blah.bin.> data.
It comes in appended to the url and the server stores it in the env variable "QUERY_STRING".
I want to C how it REALLY works... php... bah!
Thanks
  #2  
Old 12-Sep-2009, 08:58
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: how to "get" environment variables


Quote:
Originally Posted by Howard_L
...
How can I get a value from my shell into my program?

The non-standard library function getenv() is supplied with GNU compiler implementations.
CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char env_name[BUFSIZ];
    char *env_value;
    printf("Enter an environment variable name: ");
    while (fgets(env_name, sizeof(env_name), stdin)) {
        env_name[strlen(env_name)-1] = '\0'; /* Get rid of the '\n' */
        env_value = getenv(env_name);
        if (env_value) {
            printf("%s: <%s>\n", env_name, env_value);
        }
        else {
            printf("There is no environment variable named <%s>\n", env_name);
        }
        printf("Enter an environment variable name: ");
    }
    printf("\n");
    return 0;
}

Code:
Enter an environment variable name: SHELL SHELL: </bin/bash> Enter an environment variable name: CFLAGS CFLAGS: <-Wall -W -pedantic> Enter an environment variable name: xyz There is no environment variable named <xyz>

...
Quote:
Originally Posted by Howard_L
I guess system("echo blah"); goes to stdout.
Yes it does, and the the return value from system("echo anything") is equal to the return value from "echo", which is zero. (That's EXIT_SUCCESS in your C program.) See Footnote.

If you cast the return value to a pointer to char and then dereference it (by sprintf, for example) the program crashes.



Regards,

Dave

Footnote: I said that the return value from system("echo anything") is zero, and here's why:

In fact, in Linux the system command executes a fork(), and returns a value of -1 if the fork fails. If the fork is successful, it returns a value from the "anything" command.

Assuming that "echo" is the program supplied with your operating system, Is there any way that a fork to "echo" can fail? Is there any argument that you can give to the echo command that makes "echo" return anything other than zero? I don't either of these can happen, but ...
Last edited by davekw7x : 12-Sep-2009 at 10:23.
  #3  
Old 12-Sep-2009, 16:30
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: how to "get" environment variables


Quote:
Originally Posted by davekw7x
The non-standard library function getenv() ...

I wonder where my head was at. I should have said that getenv is a C and C++ standard library function. Everyone can play.

Oh, well...

Regards,

Dave
  #4  
Old 12-Sep-2009, 19:23
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 845
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: how to "get" environment variables


Thanks Dave.
re: non-standard getenv() - Glad you clarified that , I was going to ask...

getenv() is doing the trick alright.
I have put together the beginings of my C form handler which is working on my install of apache.
I included some setup information as well for anyone interested in giving it a try.
CPP / C++ / C Code:
/********************************************************************
  cform_get.c    -use environment values to handle html form method="get" input 
 ********************************************************************/
#include <stdio.h>
#include <stdlib.h>
  
int main(void)
{
  char buff[256] = {0} ;
  int  c= 0;

  printf("Content-type: text/html \n\n"); /* must be double newline for apache*/

  printf("<html><head><title>cform_get.c form handler</title></head><body>\n");
  printf("cform_get.c  -a prog to handle html form \"get\" input <br/><br/>\n\n ");
 
 /* must use &lt instead or < or the browser will think it's a tag 
     and output is stunned until it gives up looking for the other end! */
  printf("This is the raw data held in the \"QUERY_STRING\" environment variable: <br/><br/>\n\n&lt;");
 
  c = snprintf(buff, sizeof(buff), "%s", getenv("QUERY_STRING") );

  if(c > 0)
    printf("%s", buff);

  printf(">\n\n<br/><br/>The end... c = %d \n", c );
  printf("</body></html> \n");
 
  return 0;
}

/*
###################
#### To compile:
gcc -Wall -W -pedantic cform_get.c -o cform_get.bin

##########################
#### Output to Xterm:
>  ./cform_get.bin
Content-type: text/html 

<html><head><title>cform_get.c form handler</title></head><body>
cform_get.c  -a prog to handle html form "get" input <br/><br/>

 This is the raw data held in the "QUERY_STRING" environment variable: <br/><br/>

&lt;name=Chuck&n1=25&n2=30>

<br/><br/>The end... c = 21 
</body></html> 

#######################
#### Output to browser:
cform_get.c -a prog to handle html form "get" input

This is the raw data held in the "QUERY_STRING" environment variable:

<name=Chuck&n1=25&n2=30>

The end... c = 21

##################################################
#### How to set the target variable for use in the shell:

>  export QUERY_STRING="name=Chuck&n1=25&n2=30"
>  echo $QUERY_STRING
name=Chuck&n1=25&n2=30

##########################################################
#### To Set your server to execute this as CGI (cool) ####

*  First, apache must be configured to run cgi scripts.
   If you can run php and perl , it's set. (I think)
 
*  Place  cform_get.bin  in the apropriate directory (eg: /var/html/cgi-bin )

*  Create a local appache directive  file:
   ( Here I use append so as not to overwrite exsisting .htaccess file data)
 
cat >>  /var/html/cgi-bin/.htaccess
# Tell apache to run compiled C or C++ progs
AddHandler cgi-script .bin

*  Set permissions:

chmod 644 .htaccess
chmod 751 cform_get.bin

*  And you're set! (hopefully)

###########################################################
#### To create a form.html to send the prog some data  ####

cform.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>    
  <title>cform.html </title>
</head>

<body>
  <x style="font-size:120%"> cform.html &nbsp &nbsp roll my own server program! </x><br/>
  <br/>
  <br/>
  get<br />
  
  <form name='cform' method='get' action='../cgi-bin/cform_get.bin'>
                                         <!-- adjust path for your setup--> 
  Enter your name: <br/>
  <input type='text' name='name'> <br/>
  
  Enter a first number: <br/>
  <input type='text' name='n1'> <br/>

  Enter a second number: <br/>
  <input type='text' name='n2'> <br/>

  <input type='submit' value='Submit' />
  
  </form>

</body>
</html>

#### set permissions:
chmod 644 cform.html

######################################################## 

As far as setting up and configuring httpd.conf and running
the apache httpd server and all , they have great documentation! 

[url]    http://httpd.apache.org/    [/url]
*/
So what's next , method = "post" or parsing the string... I guess get post out of the way.
Thanks again; Howard++;
  #5  
Old 12-Sep-2009, 23:24
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 845
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: how to "get" environment variables


And the method="post" is easy to get too:
CPP / C++ / C Code:
/********************************************************************
  cform_post.c   -use stdin handle html form method="post" input 
 ********************************************************************/
#include <stdio.h>
#include <ctype.h>

int main(void)
{
  char buff[256] = {0} ;
  int  i, c= 0, len= sizeof(buff) ;

  printf("Content-type: text/html \n\n"); /* must be double newline for apache*/

  printf("<html><head><title>cform_post.c form handler</title></head><body>\n");
  printf("cform_post.c  -a prog to handle html form to get \"post\" input <br/><br/>\n\n ");

  /* must use &lt; instead or < or the browser will think it's a tag */
  printf("This is the raw form data read from stdin: <br/><br/>\n\n&lt;");

  for( i= 0; isprint( c = getc(stdin) ); i++)
  {
    if( i >= len)
      break;

    buff[i] = c;
  }

  if(i > 0)
    printf("%s", buff);

  printf(">\n\n<br/><br/>The end... c = %d  \n", i );
  printf("</body></html> \n");

  return 0;
}

/*
name=Marcus+Welby&n1=222&n2=333
###################
#### To compile:
gcc -Wall -W -pedantic cform_post.c -o cform_post.bin

##########################
#### Output to Xterm:  
Piped data, like form method="post", is read  from stdin so we do that here:

>  echo "Marcus+Welby&n1=222&n2=333" | ./cform_post.bin
Content-type: text/html 

<html><head><title>cform_post.c form handler</title></head><body>
cform_post.c  -a prog to handle html form to get "post" input <br/><br/>

 This is the raw data being read from stdin: <br/><br/>

&lt;name=Marcus+Welby&n1=222&n2=333>

<br/><br/>The end... c = 31   
</body></html> 

#######################
#### Output to browser:
cform_post.c -a prog to handle html form to get "post" input

This is the raw data being read from stdin:

<name=Marcus+Welby&n1=222&n2=333>

The end... c = 31

\" input <br/><br/>\n\n ");

###########################################################
#### To create a form.html to send the prog some data  ####

cform_post.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>    
  <title>cform.html </title>
</head>

<body>
  <x style="font-size:120%"> cform.html &nbsp &nbsp roll my own server program! </x><br/>
  <br/>
  <br/>
  get<br />
  
  <form name='cform' method='post' action='../cgi-bin/cform_post.bin'>
                                         <!-- adjust path for your setup--> 
  Enter your name: <br/>
  <input type='text' name='name'> <br/>
  
  Enter a first number: <br/>
  <input type='text' name='n1'> <br/>

  Enter a second number: <br/>
  <input type='text' name='n2'> <br/>

  <input type='submit' value='Submit' />
  
  </form>

</body>
</html>

#### set permissions:
chmod 644 cform.html  */
 
 

Recent GIDBlogVista ?Widgets? on Windows XP by LocalTech

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Global Variables Kalvorod C++ Forum 11 21-Feb-2007 12:07
Local variables unknown ! jvpic C++ Forum 3 10-Aug-2006 09:21
How do you SAFELY pass hidden variables through merchant account payment screens? mrsurrey eCommerce / Merchant Account Forum 4 03-Jul-2006 15:28
variables return to previous value after i try to set them nasaiya MS Visual C++ / MFC Forum 2 14-Jun-2005 00:43
[Tutorial] Pointers in C (Part I) Stack Overflow C Programming Language 1 08-Apr-2005 18:35

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 00:13.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.