Regarding background processes using fork() and child processes in my dummy shell

前端 未结 1 1872
不知归路
不知归路 2020-12-13 07:15

I\'m trying to create a simple shell program in C. What I need it to do is provide the user with a prompt in which they can run other local programs. I can do that part fine

相关标签:
1条回答
  • 2020-12-13 07:27

    You do not want to use the double-fork() method in a shell - that is for writing daemons that specifically want to escape from supervision by the shell that ran them.

    Instead, the way to duplicate the behaviour of & in existing shells is to call fork(), then in the child call setpgid(0, 0); to put the child into a new process group. The parent just continues on (perhaps after printing the PID of the child) - it doesn't call wait().

    Each terminal can have only one foreground process group, which is the process group which is currently allowed to send output to the terminal. This will remain the process group of which your shell is a member, so your shell will remain in the foreground.

    If a background process group tries to read from the terminal, it will be sent a signal to stop it. Output to the terminal is still allowed - this is normal (try ls & in your regular shell). To implement the fg command in your shell, you will need the tcsetpgrp() function to change the foreground process group.

    You will also want to call waitpid() with the WNOHANG option regularly - say, immediately before you display the shell prompt. This will allow you to detect when the background process has exited or stopped (or alternatively, you can handle the SIGCHLD signal).

    0 讨论(0)
提交回复
热议问题