【问题标题】:Fork(), one process doesn't terminate?fork(),一个进程不会终止?
【发布时间】:2017-07-23 15:46:18
【问题描述】:

我以前从未得到过这个;我正在做一个简单的程序:创建子进程的父进程,并在它终止后;这是代码

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



int child(pid_t pid)
{
    printf("process %d is terminating\n",pid);
    exit(EXIT_SUCCESS);
}

int main()
{
    int i;
    for(i = 0; i < 2; i++){
        if(fork() == 0)
            child(getpid());
    }
    printf("father, pid=%d terminated\n",getpid());
    /*if(wait(NULL) == -1)
        perror("wait");*/
    exit(EXIT_SUCCESS);
}

当我运行时,打印所有进程,但一个进程,我认为是父亲,但我不确定,不会终止,因为终端处于活动状态(不出现 $); insted,如果我插入带有等待的注释行,程序运行正确;为什么这个?

terminal output

【问题讨论】:

  • 你能发布你看到的终端输出吗?
  • 添加了它;如您所见,有时它运行正确,有时一个进程不会终止..

标签: process fork wait


【解决方案1】:

如果您查看屏幕截图中的最后一次运行,您会看到“进程 8429 正在终止”终端提示已打印到屏幕上。

似乎正在发生的是您的“父亲”进程恰好首先退出,然后您的外壳程序输出提示。然后,在最后一种情况下,子进程 (PID 8429) 打印其输出然后退出。

所以它正在终止,但有时子进程直到父进程退出并且您的 shell 进程已经打印提示后才会终止。

执行此操作时再次按“enter”,您应该会看到正确的 shell 提示。甚至输入一个命令,它应该可以正常运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 2016-04-16
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多