0

I'm trying to implement a simple unix shell in C. However, my background process feature is not working well.

When I run the shell and give a background command, it gives the output like the following:

> sleep 4 &
> [10612]retval: 0 
> [10616]retval: 0 
> [10618]retval: 0 
> [10619]retval: 0 
> [10622]retval: 0 
> [10623]retval: 0

The problem is that it gives an output with a period of sleep time while it should just give the first retval.

My signal handler is

void handler(int s) {
    int pid;
    int status;
    pid = waitpid(-1, NULL, WNOHANG);
    printf("[%d]retval: %d \n", pid, WEXITSTATUS(status));
    fflush(stdout);
}

My sigaction is

struct sigaction act;
memset(&act, 0, sizeof(act));

sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = handler;

So, what is wrong with my code?

Thanks in advance...

EDIT : Also, I have a sigaction()

if (isBackground) {
        sigaction(SIGCHLD, &act, 0);
    }
Enes Altuncu
  • 449
  • 2
  • 7
  • 14
  • 3
    Please include the complete program that exhibits the problem. See [mcve]. – sigjuice Apr 01 '17 at 13:19
  • 1
    Maybe you forgot to call sigaction() ? BTW: don't call printf() from within a signal handler. – wildplasser Apr 01 '17 at 13:27
  • Why the `WNOHANG`? – alk Apr 01 '17 at 13:41
  • 1
    The signal handler "calls" `WEXITSTATUS` on the uninitialised variable `status`: Bad thing. – alk Apr 01 '17 at 13:44
  • @alk I followed an example code. I'm open for all your suggestions. – Enes Altuncu Apr 01 '17 at 13:45
  • The call to `fflush()` is useless, as the newline in the `printf` statement before triggered flushing the stream already. Also, I already commented to your last question to *only* use async-signal-save functions inside a signal handler. – alk Apr 01 '17 at 13:47
  • I suggest you read the documentation to `wait()`/`waitpid()`. C is not the right language to learn by trial&error. – alk Apr 01 '17 at 13:47
  • Then, how can I use write() with some variables in it? – Enes Altuncu Apr 01 '17 at 13:52
  • You need to create your own formatting functions using async-signal-save functions only. Still I doubt this misplaced non-async-signal-save functions are the root-cause for the issue(s?) you are facing. – alk Apr 01 '17 at 13:54
  • The logging output you show, lists different PID's for each invocation of the signal handler. From this I conclude your code creates multiple processes. Is it expected to do this? – alk Apr 01 '17 at 13:58
  • No, it should just execute the command and show the prompt again. – Enes Altuncu Apr 01 '17 at 14:01
  • So it seems some forking code is running wild. – alk Apr 01 '17 at 14:02
  • Actually, I have just one fork. How is it possible? – Enes Altuncu Apr 01 '17 at 14:03
  • By the way, I tried to remove printf ,but nothing has changed. So, the problem is on something different. – Enes Altuncu Apr 01 '17 at 14:05

0 Answers0