在C语言中,可以使用'fork()'函数创建一个子进程。在子进程中使用'getpid()'函数获取自己的进程ID,在父进程中使用'getpid()'函数获取自己的进程ID,再使用'fork()'返回的值获取子进程的进程ID。以下是一个示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    pid_t pid = fork();

    if (pid < 0) {
        fprintf(stderr, "Fork failed\n");
        return 1;
    } else if (pid == 0) {
        // 子进程
        printf("Child process: My PID is %d\n", getpid());
        printf("Child process: My parent's PID is %d\n", getppid());
    } else {
        // 父进程
        printf("Parent process: My PID is %d\n", getpid());
        printf("Parent process: My child's PID is %d\n", pid);
    }

    return 0;
}

在执行该程序后,会分别在子进程和父进程中打印对应的ID号。

至于第二个问题,打开一个新的终端输入'ps -ef'命令查看程序的ID号,结果是不同的。因为'ps -ef'命令会列出所有正在运行的进程,而我们的程序只是临时运行一段时间,执行完后就结束了,所以在运行'ps -ef'命令时,我们的程序已经不存在了。如果要查看程序的进程ID号,可以在程序执行过程中使用'ps -ef'命令。

C语言:子进程与父进程ID获取及查看方法

原文地址: https://www.cveoy.top/t/topic/qwtN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录