【问题标题】:Can a process have two PIDs?一个进程可以有两个PID吗?
【发布时间】:2012-10-09 05:13:27
【问题描述】:

我正在研究计算机系统,我制作了这个非常简单的函数,它使用fork() 创建一个子进程。 fork() 返回一个 pid_t 如果它是一个子进程则为 0。但是在这个子进程中调用getpid() 函数会返回一个不同的、非零的pid。在我下面的代码中,newPid 是否仅在程序上下文中有意义,对操作系统没有意义?它可能只是一个相对值,根据父级的 pid 衡量吗?

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

void unixError(char* msg)
{
    printf("%s: %s\n", msg, strerror(errno));
    exit(0);
}

pid_t Fork()
{
    pid_t pid;
    if ((pid = fork()) < 0)
        unixError("Fork error");
    return pid;
}


int main(int argc, const char * argv[])
{
    pid_t thisPid, parentPid, newPid;
    int count = 0;
    thisPid = getpid();
    parentPid = getppid();

    printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);

    if ((newPid = Fork()) == 0) {
        count++;
        printf("I am the child. My pid is %d, my other pid is %d\n", getpid(), newPid);
        exit(0);
    }
    printf("I am the parent. My pid is %d\n", thisPid);
    return 0;
}

输出:

thisPid = 30050, parent pid = 30049
I am the parent. My pid is 30050
I am the child. My pid is 30052, my other pid is 0

最后,为什么孩子的 pid 2 比父母的高,而不是 1? main 函数的 pid 和它的 parent 之间的差是 1,但是当我们创建一个 child 时,它会增加 2 的 pid。这是为什么呢?

【问题讨论】:

    标签: c fork pid


    【解决方案1】:

    来自 fork man 页面:

    返回值

    成功时,子进程的PID在父进程中返回, 并且在孩子中返回 0。失败时,-1 在 parent,没有创建子进程,并且设置了适当的errno。

    Fork 不返回子进程的 pid,只在父进程中返回。因此,子进程没有两个pid。

    试试这个

    int main(int argc, const char * argv[])
    {
        pid_t thisPid, parentPid, newPid;
        int count = 0;
        thisPid = getpid();
        parentPid = getppid();
    
        printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
    
        if ((newPid = Fork()) == 0) {
            count++;
            printf("I am teh child. My pid is %d\n", getpid());
            exit(0);
        }
        else
           printf("I am the parent. My pid is %d, my child pid is %d\n", thisPid, newPid);
        return 0;
    }
    

    【讨论】:

    • 我想您想在孩子中打印来自getpid 的结果?现在它正在打印 0。
    【解决方案2】:

    PID 在分配时不是连续的(实际上不遵循任何规则),一个进程一次只有一个 PID。此外,永远不可能有两个进程共享相同的 PID。

    【讨论】:

      【解决方案3】:

      Pid 是每个进程一个。一个进程永远不会有超过 1 个 pid - 在操作系统中处理进程的内部数据结构中只有一个 PID 字段。

      除此之外,当您调用 fork() 时,您正在克隆调用 fork 的进程,生成一个完全相同的副本 - 所有文件句柄、所有内存等。除了它的 PID。这就是为什么 fork 根据您是子进程还是父进程返回不同值的原因。这种不同的返回值让程序知道它是孩子还是父母。孩子得到 0,因此可以知道它是孩子。

      【讨论】:

        【解决方案4】:

        不,一个 pid 一次只分配给一个进程。

        进程 ID 在分配给进程时不需要遵循任何规则。因此,如果看起来子 pid 是父 pid 的增量,这只是运气。

        通过某些进程的 pid,不可能得出有关进程关系的任何结论。

        【讨论】:

          猜你喜欢
          • 2018-07-05
          • 1970-01-01
          • 2011-09-01
          • 1970-01-01
          • 2017-08-30
          • 2010-10-01
          • 2016-07-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多