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

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.


Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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


(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,
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

>> 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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.


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,
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.