• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 492
  • Last Modified:

Trying to make a Shell program - some errors

I'm trying to learn some C++ and thus want to make a small test program in the form of a command-line intrepeter. However, I'm getting a segmentation fault in the childprocess and a guy I talked to who knows programming a lot better than me said there was two faults in line 82, and that I should also clean up the amounts of zombie processes by adding the following line
while(waitpid(0,&status,WNOHANG|WUNTRACED)>0);

What he forgot to tell me is where to add that line though. Although I had a bunch of other errors, I managed to fix most of them (I think), but those two still remain a small mystery to me. Problem is he's in Australia on vacation for the next month, so I have a hard time getting a hold of him. Thus I ask the question here.

I removed the comments as they're in norwegian in any case (would have been very confusing :P). I'll mark "line 82" with a big comment for you :)

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "safefork.c"

#define MAX 250

extern char **environ;
char **path;
char *pathstart;
int ant_path;

int main(void) {
  char cmd[MAX], prev[MAX];
  char *param[30];
  char *pathen;
  char *arg;
  int ant_param, tom, ws, amp, i, status;
  pid_t pid, n;
 
  get_path();

  while(1){
    ant_param = 0;
    amp = 0;
    ws = 0;
    tom = 0;

    printf("ifish>");
   
    if(fgets(cmd, MAX, stdin) == NULL) exit(1);

    if(strcmp(cmd, "exit\n") == 0) exit(1);
   
    if(strcmp(cmd, "\n") == 0) tom = 1;
 
    if(tom == 0) {
      cmd[strlen(cmd)-1] = '\0';
     
      if(strcmp(cmd, "!!") == 0) strcpy(cmd, prev);
     
      strcpy(prev, cmd);
     
      amp = sjekk_og(cmd);
      arg=strtok(cmd, " ");
     
     
      param[0] = arg;
     
      do{
      
      param[++ant_param] = strtok(NULL, " ");
      }
      while(param[ant_param] != NULL);
     
      pid = safefork();
     
      if(pid == 0){
      for(i=0; i<ant_path;i++) {
        pathen = malloc(strlen(path[i]+1)); //*******LINE 82********
        strcpy(pathen, path[i]);
        strcat(strcat(pathen, "/"), arg);
        execve(pathen,param,environ);
        
        free(pathen);
      }
      printf("ifish: %s: Command not found\n", param[0]);
      exit(1);
      }
      else {
      if(amp == 0){
        do{         
          n = wait(&status);
        }
        while(n != pid);
      }
      else {
        printf("Pid: %d\n", pid);
      }
      }
    }
  }
}//slutt main

int sjekk_og(char *cmd) {
  char *og;
  og = strrchr(cmd, '&');
  if(og != NULL)
    if(*++og == '\0' || *og == ' ') {
      *--og= '\0';
      return 1;
    }
  return 0;
}

int get_path() {
  int i;
  char *pathcpy;
  pathstart = getenv("PATH");
  pathcpy = strdup(pathstart);
  pathstart = pathcpy;
 
  while(1) {
    if(*pathcpy == '\0') {
      i = 0;
      break;
    }
    if(*pathcpy == ':') ant_path++;
    pathcpy++;
  }
  ant_path++;
  path = malloc(sizeof(char*)*ant_path);
  path[0] = strtok(pathstart, ":");
 
  for(i=1; i<ant_path; i++) path[i]=strtok(NULL, ":");
 
  return 1;
  free(path);
}




and safefork.c looks like this:

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/errno.h>

extern int errno;

#define MAX_PROCESSES 6

static int n_processes(void)
{
  return system("exit `/local/bin/ps | /local/bin/wc -l`")/256;
}


pid_t safefork(void)
{
  static int n_initial = -1;
 
  if (n_initial == -1)
    n_initial = n_processes();
  else if (n_processes() >= n_initial+MAX_PROCESSES) {
    sleep(2);
    return -EAGAIN;
  }
 
  return fork();
}

PS: the safefork.c was something my friend gave me. Said it was safer to start with than the normal fork operations.

Anyways, any help is appreciated.

Thanks,
ZombieBobie

0
ZombieBobie
Asked:
ZombieBobie
  • 3
  • 2
  • 2
2 Solutions
 
DanRollinsCommented:
You have failed to initialize ant_path.

      int ant_path= 0;

You need to debug the program.  Place a breakpoint on the line you marked as LINE 82 and use the debugger to examine the relevant variable each time that line is hit.  Then singlestep across that line.

-- Dan
0
 
ZombieBobieAuthor Commented:
mmm... talked to a guy who suggested changing line 82 to

pathen = malloc(strlen(path[i]) + 1 + strlen(arg));

to fix the seg. fault error... not sure if it works yet though. Any comments?

and I've not found where to place the while loop yet.

as for the ant_path = 0, that doesn't really matter when it comes to the problem with line 82 etc does it?

on the other hand, do you know of a good debugger? (free preferably).

thanks for the reply though

-ZombieBobie
0
 
bcladdCommented:
ZombieBobie-

(1) I am assuming you are running on some *nix OS. If you're compiling with g++/gcc I would suggest you investigate gdb. Future note is to make sure you know your tools when you start working on a system.

(2) The admonition against experts helping you do your homework probably applies to telling you whether or not the code "some other guy" suggested you put in would help the problem. If line 82 is the focus of your concern, what does line 82 DO? DanRollins suggestion that you use a debugger would permit you to answer the question by looking at the variables.

Just a comment: You need to understand what your code does because I have never had a student finish even the first shell program assignment without knowing C/C++ and understanding how to debug it. Understand your code (and what "safefork" does).

Good luck,
-bcl
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
DanRollinsCommented:
>> ant_path = 0, that doesn't really matter when it comes to the problem with line 82 etc does it?

Yes, it does.  Look at how the value of ant_path gets set.  One way to do that is to do a search for all occurrences of that string in your program.

And ant_path is the upper limit on your loop, so it affects the value of  the variable i,  which is used in that line.

-- Dan
0
 
ZombieBobieAuthor Commented:
bcladd, it's not homework, im doing it on my own in preparation for next years classes(which are said to be highly difficult). My current classes are all on Java. Thus I'm not *that* familiar with memory allocation and pointers. That lead to me having some difficulties with malloc commands.

As for the "some guy" he's a bot programmer for an old online game called SubSpace/Continuum, and the friend of mine I got checking my code now and then works for Siemens and have taken similar courses to the ones Im taking next year, so he showed me the ropes and gave me a few tidbits to try out.

If its still in violation of anything, then I'm sorry and I'll ask around elsewhere.

PS: I'm not using gcc as safefork uses some local variables.
--

Dan, I'll see if I can find a decent debugger and give it a twirl. If it works, I'll come back and give you your points. Thanks.

-ZombieBobie
0
 
bcladdCommented:
ZombieBobie-

You're not in "violation" and I am, at best, an imperfect conscience rather than any sort of enforcer.

What I urged, that you understand your code, goes double if you are investing your time against future courses. Really, work on understanding the various pieces of your code and if your friend is helping you, the greatest help he can give it to explain the small pieces he gives you.

What compiler ARE you using? I ask because there are some free debuggers out there (Borland had the Turbo Debugger that sometimes works with BCC5.5 (I say sometimes because it is a generation out of date compared to the compiler)).

I think DanRollins has found the cause of this particular problem in his last post. You still might want to look for a debugger for your system.

Good luck,
-bcl
0
 
DanRollinsCommented:
In the absense of a debugger, it is still possible to debug.  Place printf lines at various places.  like:

      printf("DEBUG: value of i is %d \n", i );

at the top of that loop.   Scatter them around all over the place and that gives you a toehold into the code.

-- Dan
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now