Home > Back-end >  i'm trying to do this thing i saw in a textbook, to set environment variables but it seems i�
i'm trying to do this thing i saw in a textbook, to set environment variables but it seems i�

Time:08-02

Can someone please help me figure out why i'm not getting the results im supposed to?from the textbook

my code on vscode

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *my_env[] = {"JUICE = peaches and apples", NULL};
    execle("diner info", "diner info", "4", NULL, my_env);

    printf("Diners: %s\n", argv[1]);
    printf("Juice env: %s\n", getenv("JUICE"));
    return 0;

}

my results are Diners: (null) and Juice env: (null)

CodePudding user response:

Try it as it is shown in the text book:

They are 2 programs:

The first program prepares an environment and passes it to a second program that it also executes.

// my_exec_program.c
#include <unistd.h>

int main(void)
{
    char *my_env[] = {"JUICE=peaches and apples", NULL};
    execle("diner_info", "diner_info", "4", NULL, my_env);
}

The second program reads its environment and prints it.

// diner_info.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  if (argc > 1)
  {
    printf("Diners: %s\n", argv[1]);
  }
  printf("Juice env: %s\n", getenv("JUICE"));
  return 0;
}

Terminal:

gerhardh@xy:~/tests$ gcc -Wall -Wextra -pedantic my_exec_program.c -o my_exec_program
gerhardh@xy:~/tests$ gcc -Wall -Wextra -pedantic diner_info.c  -o diner_info
gerhardh@xy:~/tests$ ./diner_info 
Juice env: (null)
gerhardh@xy:~/tests$ ./my_exec_program 
Diners: 4
Juice env: peaches and apples
gerhardh@xy:~/tests$ 

Mixing the code and squeezing everything into one file will not work.

  • Related