Skip to content

Instantly share code, notes, and snippets.

@Ulu2005
Created October 22, 2014 14:38
Show Gist options
  • Save Ulu2005/1af2a49edd97fc3af63e to your computer and use it in GitHub Desktop.
Save Ulu2005/1af2a49edd97fc3af63e to your computer and use it in GitHub Desktop.
/*
* waitfg - Block until process pid is no longer the foreground process
*/
void waitfg(pid_t pid) {
sigset_t mask, nomask, old;
struct job_t *j = getjobpid(jobs, pid);
sigfillset (&mask);
sigemptyset (&nomask);
sigprocmask (SIG_SETMASK, &mask, &old);
/*At this point, all signals are blocked.
There is no way a child can be terminated before
sigsuspend is called, so we're guaranteed to catch
the SIGCHLD now.
However, before calling sigsuspend, I make sure that the
process hasn't terminated quickly.
Without this check, I could wait forever for a signal that will
never arrive.*/
if (j && j->pid == pid) // job still there?
while (j->pid == pid && j->state == FG)
sigsuspend (&nomask); // any signal wakes up the sigsuspend
sigprocmask (SIG_SETMASK, &old, NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment