Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何通过查看代码来确定子进程是后台进程还是前台进程?_C_Linux_Shell_Process - Fatal编程技术网

C 如何通过查看代码来确定子进程是后台进程还是前台进程?

C 如何通过查看代码来确定子进程是后台进程还是前台进程?,c,linux,shell,process,C,Linux,Shell,Process,我们知道,如果父进程首先等待其子进程的终止,则子进程称为前景进程,例如: int main() { int status; ... if ((pid = fork()) == 0){ ...// Child runs exit(0); } waitpid(pid, &status, 0); //parent wait for its child to reap it } 由于父进程使用waitpid等待并获取其子进程,因此子进程是

我们知道,如果父进程首先等待其子进程的终止,则子进程称为前景进程,例如:

int main() {
   int status;
   ...
   if ((pid = fork()) == 0){
      ...// Child runs
      exit(0);
   }
   waitpid(pid, &status, 0);  //parent wait for its child to reap it
}
由于父进程使用
waitpid
等待并获取其子进程,因此子进程是前台进程

但是,如果我使用信号处理程序来获取子进程,会怎么样呢

void sigchld_handler(int s){
   int olderrno = errno;
   pid = waitpid(-1, NULL, 0);
   errno = olderrno;
}

volatile sig_atomic_t pid;

int main() {
   sigset_t mask, prev;
   signal(SIGCHLD, sigchld_handler);
   sigemptyset(&mask);

   while(1) {
      sigprocmask(SIG_BLOCK, &mask, &prev);  // Block SIGCHLD      
      if ((pid = Fork()) == 0){
          ...// Child runs
          exit(0);
      }
      // Wait for SIGCHLD to be received 
      pid = 0;
      while (!pid)
         sigsuspend(&prev);
      ...//Do some work after receiving SIGCHLD
   }
   exit(0);

}
那么我可以说后者中的子进程是前台进程,因为父进程使用
while(!pid)sigssuspend(&prev)等待它


但我的理解是,只有当父进程在
waitpid
中明确表示子进程id时,子进程才能成为前台进程,就像
waitpid(pid,&status,0)waitpid
中使用
-1
)?

用于运行程序的术语“前台”和“后台”更像是一个shell。你自己的
fork
进程没有这样的区别。@Someprogrammerdude如果我在这个问题中的代码是一个shell,那么子进程是在后一个前台还是后台?如果你的程序是一个shell,它是否在另一个程序运行时接受新命令?然后该程序在“后台”运行。否则它将在“前台”运行。这是唯一的区别。