运行的过程中在C背景 [英] running a process in background in c

查看:92
本文介绍了运行的过程中在C背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从main函数C运行在后台子进程。我用叉子和execv函数来这样做。但我也想杀死孩子后台进程,在父进程结束,如果子进程还没有退出。我将使用kill(pChildPid)函数来做到这一点。所以我的问题是

I want to run a child process in background from main function in c. I have used fork and execv functions to do so. But I also want to kill the child background process, at the end of the parent process, in case the child process has not exited yet. I will be using kill(pChildPid) function to do so. So my question is

假设子进程的父进程退出之前,可以在Linux操作系统可以分配的PID为那个孩子一样到其他进程?如果是,那么我将无意中杀死进程?

Suppose the child process has exited before the parent process, can linux OS can allocated the same pid as that of child to some other process? If yes, then I will be unintentionally killing that process?

推荐答案

是的,理论上是可以的,是的,你可以。

Yes, in theory, it can, and yes you can.

不过,如果你拥有的过程中,这将是一个僵尸过程,直到你的 waitpid函数或类似的功能已经收到这个过程死亡消息[除非分叉的过程中使用分离从拥有进程断开。

However, if you OWN the process, it will be a "zombie" process until your waitpid or a similar function has received the message that the process died [unless the forked process uses detach to disconnect from the owning process].

要证明:

#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>

int main()
{
    int pid = fork();
    if (pid)
    {
        int p = 0;
        int status;
        sleep(60);
        p = wait(&status);
        std::cout << "Pid " << p << " exited..." << std::endl;
    }
    else
    {
        for(int i = 0; i < 20; i++)
        {
            std::cout << "Child is sleeping..." << std::endl;
            sleep(1);
        }
        std::cout << "Child exited..." << std::endl;
    }
    return 0;
}

如果你运行这一点,并使用 PS A 来查看过程中,您将看到的a.out 两次,PID的接近对方。一旦它打印子退出,你会看到第二个过程的状态去是这样的:

If you run this, and use ps a to view the processes, you'll see a.out twice, with PID's close to each other. Once it prints child exited, you'll see that the status of the second process goes to something like:

12362 pts/0    Z+     0:00 [a.out] <defunct>

下面Z表示,这是一个僵尸的过程。当第一个进程的60秒以上,它然后消失。

Here Z means that it's a "zombie" process. When the 60 seconds of the first process is over, it then disappears.

这篇关于运行的过程中在C背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆