I have asked a similar question but after revisiting some of my code I remembered from where the main issue stemmed from, here is the link to the old question.
How to implement built-in commands for my C shell with job control that change the state or environment of the shell process, such as chdir
, setenv
, exit
... when they are specified to run in background by the user.
Meaning these commands should not block terminal input when being executed as is the nature of background job processes.
One way to achieve executing built-in commands to not block the terminal input would be to fork()
the shell process and execute them there, but this won't change/affect the main shell process instead the child would get its state changed which is not desired behaviour. Although this approach is applicable to non-state main process changing built-in commands.
My approach to this originally was to:
- have a separate routine prior to forking
- this routine would first
dup()
stdin
,stdout
,stderr
streams - now
dup2()
pipe streams - then check if any of the built-in commands that change the state should get executed
- if yes, parse user redirections if any and built-in command/function is executed blocking the terminal input...!
- at the end no matter if the command was executed or not we restore the saved default (terminal) streams
stdin
,stdout
,stderr
withdup2()
calls. - function will have to return some kind of integer for status and in case it didn't run a negative integer which will be checked later to determine if we need to
fork()
to run the command or maybe a control integer/bool ptr as additional parameter to the function.
Resolving the redirections could be done prior and then reuse them in case we need to fork but this is not the concern, anyways this approach leads to terminal input being blocked, is there any workaround? Or is there just a better way of doing things like this?