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

℡╲_俬逩灬. 提交于 2019-12-02 05:33:26

问题


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 am trying to write a shell that can start processes either in the foreground or background.


回答1:


"Background" and "foreground" are not terms used generically for processes, but rather only apply to shells which can wait for jobs on demand.




回答2:


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



回答3:


you can do use fg to bring process to foreground and bg to put process to background. you should know the pid of the process to bring it to foreground. refer linux manual of fg and bg for more info



来源:https://stackoverflow.com/questions/5785988/how-to-bring-a-child-process-running-in-the-background-to-the-foreground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!