0

I am trying to write a simple shell program, but have a small bug, which I can't seem to solve.

The program should be capable of launching a background process, but it fails to do so properly. It seems to work at first (program launches & the shell is still responsible) but fails at the second command.

In other words what happens is

  • launch some background process (browser) - works (launches and keeps working)
  • launch some regular process - works (lunches & finishes)
  • launch another process - doesn't work. The shell isn't responsive and waits until the background process is over.

Removing the following line:

   waitpid(pid,NULL,0);

Solves this issue, but now all programs are 'background' (shell won't wait for anything to finish).

This is the complete function:

int launchprog(int background, char** arglist){
 /* create a background process*/
if(background == 1){
    pid_t pid = fork();
    if(pid == 0){
         /* child*/
        arglist[-1] = NULL;
        if (execvp(arglist[0], arglist) == -1) {
            perror("Error in execvp, cannot init child process");
        }
        exit(1);
    } else if (pid < 0) {
        perror("Forking error");
        exit(1);
    }
    return 1;
}

/* create a simple process*/

printf("shalom, %d,%d\n", background,getpid());



pid_t pid = fork();

if (pid == 0) {
    /* child*/

    struct sigaction saint;
    saint.sa_handler = &int_signal_handle_exit;
    sigemptyset(&saint.sa_mask);
    saint.sa_flags = 0;
    if (sigaction(SIGINT, &saint, 0) == -1) {
        perror("Sigaction Error");
        exit(1);
    }

    if (execvp(arglist[0], arglist) == -1) {
        perror("Error in execvp, cannot init child process");
    }
    exit(1);
}
else if (pid < 0) {
    perror("Forking error");
    exit(1);
} else {
    if (background == 0){ /* this should always be true*/
        waitpid(pid,NULL,0);
    }
}
return 1;
}
chepner
  • 497,756
  • 71
  • 530
  • 681
Laetus
  • 101
  • 1

0 Answers0