Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Trying to make a Shell program - some errors

Posted on 2003-11-16
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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,
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.

LVL 49

Accepted Solution

DanRollins earned 1200 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 300 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

618 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