Solved

Trying to make a Shell program - some errors

Posted on 2003-11-16
7
479 Views
Last Modified: 2010-04-01
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
Comment
Question by:ZombieBobie
  • 3
  • 2
  • 2
7 Comments
 
LVL 49

Expert Comment

by:DanRollins
ID: 9760312
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
 

Author Comment

by:ZombieBobie
ID: 9760343
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
 
LVL 11

Expert Comment

by:bcladd
ID: 9761032
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 49

Accepted Solution

by:
DanRollins earned 400 total points
ID: 9762551
>> 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
 

Author Comment

by:ZombieBobie
ID: 9762950
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
 
LVL 11

Assisted Solution

by:bcladd
bcladd earned 100 total points
ID: 9762993
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
 
LVL 49

Expert Comment

by:DanRollins
ID: 9767136
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question