extern: command not found

Viewed 566

I'm following along with this lab from a Udemy course on computer security which primarily uses C (I think) scripts for demonstrations. After trying to run the following program on my own computer (in both an Ubuntu and MacOS environment), I get so many errors that it seems as if the compiler doesn't even know what language it's reading.

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

extern char **environ;

void printenv()
{
  int i = 0;
  while (environ[i] != NULL) {
    printf("%s\n", environ[i]);
    i++;
  }
}

void main()
{
  pid_t childPid;
  switch(childPid = fork()) {
    case 0: /* child process */
      printenv();
      exit(0);
    default: /* parent process */
      //printenv();
      exit(0);
  }
}

The errors:

line 4: extern: command not found
line 5: syntax error near unexpected token '('
line 5: 'void printenv()'

Does anyone know what's going on? I'm unfamiliar with C (mostly work in Javascript and Python), but it seems like everything is pretty standard syntax and shouldn't be erroring.

1 Answers

the following proposed code:

  1. cleanly compiles
  2. performs the desired functionality
  3. does not try to produce a zombie

Note: I compiled this, on linux with:

gcc   -O1  -ggdb -Wall -Wextra -Wconversion -pedantic   -c "untitled2.c"  -I. 

Note: I linked it with:

gcc   -ggdb -Wall -o "untitled2" "untitled2.o"

However, fork() can fail, in which case it returns -1, so the code should have a

case -1:
    perror( "fork failed" );
    break;

and now, the proposed code:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

extern char **environ;

void printenv()
{
  int i = 0;
  while (environ[i] != NULL) {
    printf("%s\n", environ[i]);
    i++;
  }
}

int main( void )
{
  pid_t childPid;

  switch(childPid = fork()) 
  {
    case 0: /* child process */
      printenv();
      exit(0);

    default: /* parent process */
      //printenv();
      waitpid( childPid, NULL, 0);
      exit(0);
  }
}
Related