1

I want to send my child process to the background when there is a & symbol at the end.

I tried to do the following code in my child process, currently, the shell has a foreground gid of 1000, and the child also has a foreground group id of 1000. But since now the child has a pgid of 2000, which is not the same as the parent's pgid, it would be easy if I just change my child process's foreground gid to NOT be the same as the shell's.

// we are in the child process.
/* if it is in the background mode, we want to set the child process's
   foreground id to not be the same as the terminal's foreground id, so
   that the child process can run in the background. */
   if(back_signal){
       tcsetpgrp(0, child_gpid);
   }

But, I think the above is wrong, because the function tcsetpgrp() makes the process group with process group ID pgrp the foreground process group on the terminal associated to fd, which means, tcsetpgrp(0, child_gpid) only set the child process to be another foreground process.

In short, I am stuck on how to make a child process running in the background. In addition, I didn't find any source code for fg and bg yet, if you know, please help me. Thanks in advance.

Tony Lucas
  • 189
  • 1
  • 13
  • 3
    Tony, please provide [A Minimal, Complete, and Verifiable Example (MCVE)](http://stackoverflow.com/help/mcve). You are forking a new process right? It is unclear how you end up at the conditional shown. – David C. Rankin Jul 10 '19 at 04:15
  • @DavidC.Rankin I think it is not very hard to understand, I still don't know what to do. – Tony Lucas Jul 10 '19 at 06:51

1 Answers1

0

According to this answer:

How do I get tcsetpgrp() to work in C?

It is not possible to create a child process whilst in the child process already, but rather needs to be called in the parent process.

GMoney
  • 139
  • 1
  • 11
  • thanks, your answer is correct, but do you know how to stop a child process from printing output so that it won't mess up my next command? – Tony Lucas Jul 10 '19 at 13:48
  • User has made a second question to follow this up at [link](https://stackoverflow.com/questions/56948207/dont-know-how-to-use-tcsetpgrp/56983129#56983129) Please accept this answer if it is correct – GMoney Jul 11 '19 at 06:46