How to bring a child process running in the background to the foreground

后端 未结 3 811
借酒劲吻你
借酒劲吻你 2021-01-14 05:25

If I used fork() and execv() to spawn several child processes running in the background and I wanted to bring one of them to the foreground, how could I do that?

I a

3条回答
  •  执笔经年
    2021-01-14 06:09

    Complimentarily to Ignacio Vazquez-Abram's answer, I suggest that you emulate the shell foreground/background model.

    As far as I can tell, backgrounding a process means suspending it. The easiest way to do this is through SIGSTOP. When you foreground a process, send it SIGCONT. As long as only one of your "jobs" are currently in the foreground, it will be the only one read and writing to the session's tty.

    kill(child_pid, SIGSTOP);
    kill(child_pid, SIGCONT);
    

    You may want to suspend each process after you fork, and before you execv, and give the user of your shell the option to foreground them later to maintain the invariant.

    if (!fork()) { // we are the child
        raise(SIGSTOP); // suspend self
        execv(...); // run the command (after we've been resumed)
    

    Here are some related links I found:

    • sending a signal to a background process
    • How to properly wait for foreground/background processes in my own shell in C?
    • http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_01.html

提交回复
热议问题