Trying to make a Shell program - some errors

Posted on 2003-11-16
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

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;

    ant_param = 0;
    amp = 0;
    ws = 0;
    tom = 0;

    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;
      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);
      printf("ifish: %s: Command not found\n", param[0]);
      else {
      if(amp == 0){
          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;
    if(*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;

and safefork.c looks like this:

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

extern int errno;


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) {
    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.


Question by:ZombieBobie
  • 3
  • 2
  • 2
LVL 49

Expert Comment

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

Author Comment

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

LVL 11

Expert Comment

ID: 9761032

(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,
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

LVL 49

Accepted Solution

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

Author Comment

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.

LVL 11

Assisted Solution

bcladd earned 100 total points
ID: 9762993

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,
LVL 49

Expert Comment

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Load and store *.pnm image file 1 76
Need some help with listview limit text 20 98
thread-safe code in c++ 2 84
How to gracefully close the c++ 11 thread? 3 83
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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 viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

867 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now