0

I have token[0] variable that determines whether the input cmd is foreground process or background process. When token[0] is '&' it means it is background process and if it is not, it means it is foreground process. I want to print pid if it is background process. Otherwise, I want to wait until foreground process exits. I am not sure about how to wait until foreground process exits. Code is like below.

for(i = 0; i < npids; i++) {
                //  wait for the foreground processes or print pids for the background processes
                //1. if token[0] == '&', cmd is a background process. Print its pid.
                //2. otherwise, cmd is a foreground process. Wait until it exits.
                if(token[0] == '&'){
                    printf("%d", getpid());
                }
                else{
                //Not sure
                }

After that, I want to use waitpid() with -1 for the pid and WNOHANG option to reap child processes. Also print terminated processes' pid. Like code below. What is the best way of doing it?

        printf("%d - exited", getpid());

Appreciate for your answers in advance.

dkssud
  • 3
  • 4
  • `waitpid` will return the pid of the exited process, except when it doesn't. It could also return `0` if the `WNOHANG` option was used and no process has exited. It could return `(pid_t)-1` on error. So save the return value from `waitpid` and check its value. – Ian Abbott May 11 '20 at 16:12
  • Please post a [mcve] so we can recreate the problem and help you debug it. – user3629249 May 12 '20 at 15:21

0 Answers0