一个进程可以有两个PID吗?

标签 c fork pid

我正在研究计算机系统,我制作了这个非常简单的函数,它使用 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

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

最佳答案

来自 fork man页面:

Return Value

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

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;
}

关于一个进程可以有两个PID吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959843/

相关文章:

无法访问地址为 ""的内存 (gdb)

c - 强制软件实现 opengl 3.x

c++ - 打印指针变量的地址

c++ - fork 并执行许多不同的进程,并从每个进程中获取结果

c - 创建守护进程时离开调用 setsid() 有什么影响?

c - Xlib - 获取桌面 "Work Area"

使用 printf 时,C fork 是父级的副本

erlang - 有人可以解释一下 Erlang 中 Pid(进程标识符)的结构吗?

linux - 作为守护进程运行程序返回错误的 pid

java - 如何获取我刚刚在 java 程序中启动的进程的 PID?