0

I am trying to implement background jobs in C for my shell. The problem is it prints the output next to my prompt like this:

user@hostmachine:/.../$: [output]

I have now learnt that "stty tostop" helps suspend process just before it's output but that only works in a shell. I am trying to implement this functionality in C, so that it doesn't use my terminal during a prompt.

I tried to run "stty tostop" after starting my shell but it din't work. I also asked a related question before and now I am stuck here.

amogh
  • 15
  • 6
  • 1
    If your goal is just to have software not "use your terminal"... isn't that a job for redirection? It's not generally good practice to make software depend on its output going to a TTY at all in the first place, so relying on TTY-specific configuration is making things more fragile than they need to be. – Charles Duffy Dec 13 '22 at 22:02
  • (_oh_, you're writing a shell; it might be worth mentioning that in the question explicitly. Note, though, that conventional shells _do_ let background processes print data next to / after the prompt; in trying to do something different, you're liable to be breaking user expectations -- particularly, expectations that a background process will keep running without interruptions without any explicit attempt to interrupt it) – Charles Duffy Dec 13 '22 at 22:06
  • @CharlesDuffy redirect or do not output anything – 0___________ Dec 13 '22 at 22:06
  • @0___________ What if I want to execute "ls &"? – amogh Dec 13 '22 at 22:08
  • @CharlesDuffy That's true but not if I first execute "stty tostop" first. But this command does not work in my shell and I want some advice on implementing it. Or at least making it work. – amogh Dec 13 '22 at 22:11

1 Answers1

3

Processes in the foreground process group of a given terminal can write to that terminal without being suspended. Others cannot. Thus, to put a process in the background is to put it in a process group other than than one currently in the foreground (setpgrp()).

Use tcsetpgrp() to control which process group is in the foreground on a given terminal. This is part of how you would bring your background process to the foreground.

You might find Glibc's discussion of Implementing a Job-Control Shell useful for more details and related considerations.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Could you give me an example in a code snippet? I am finding it difficult to wrap my head around it. – amogh Dec 13 '22 at 22:28
  • Evidently, @amogh, you did not make use of the links I already provided in this answer, especially the one that I specifically suggested as useful for more details. You will find some appropriate example code there, plus a lot more information that you probably need to know to get this working. – John Bollinger Dec 14 '22 at 19:03