0

我被问到这个问题做家庭作业,我很难弄清楚。如果有人可以帮助我,我将不胜感激。

什么Linux库函数类似于fork(),但是父进程被终止了?

4

2 回答 2

2

我相当肯定,无论是谁给你分配了这个作业exec(),都是从POSIX API 标头中寻找函数系列<unistd.h>,因为没有什么比你描述的那种功能更接近的了。

exec()函数族执行一个新进程,并用新执行的进程替换当前运行的进程地址空间。

手册页

exec() 系列函数用新的进程映像替换当前进程映像。

它与“终止”父进程并不完全相同,但实际上它会导致类似的情况,即父进程的地址空间被子进程的地址空间擦除(替换)。

于 2013-04-24T02:10:30.697 回答
0

什么Linux库函数类似于fork(),但是父进程被终止了?

父进程不应该终止,因为它必须等待子进程完成执行,之后它们将处于一种称为“僵尸状态”的状态,现在清理子进程的剩余部分是父进程的责任. 父进程可以在不清理子进程的情况下终止,但这不是正确的方法,因为子进程的退出状态应该由父进程收集和检查。

这是一个示例,以演示我刚才所说的...

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>

int main()
{
  pid_t cpid = 1 ;
  int status;

  cpid = fork();

  // Load a application to the child using execl() , and finish the job

  printf("Parent waiting for child to terminate\n");

  int wait_stat = waitpid(-1,&status,0);     // Parent will hang here till all child processes finish executing..
  if (wait_stat < 0)
  {
    perror("waitpid error");
    exit(-1);
  } 

  // WIFEXITED and WEXITSTATUS are macros to get exit status information, of the child process

  if (WIFEXITED (status))          
  {
  printf("Child of id %u cleaned up\n",wait_stat);
  printf("Exit status of application = %u\n",WEXITSTATUS(status));
  }

}
于 2013-04-24T02:33:16.723 回答