c - 在 fork() 之后打印子编号

标签 c unix operating-system

我正在读一本关于操作系统的书,并且对 C 编程也相当陌生(往往会使事情变得复杂),但我很好奇为什么当每个子项都是通过 fork() 创建时我无法打印递增的 i 值。它与子进程有关还是其他原因?提前致谢。

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

int main ()
{
    pid_t pid;
    int i = 1;

    pid = fork();
    pid = fork();
    pid = fork();
    pid = fork();

    if (pid == 0) {
        printf("got child %d\n", i);
        i++;
    }
}

最佳答案

使用 getpid()getppid() 获取父进程和子进程 ID。

示例为here

int main()
{

        int i;
        printf("hello before fork \n");
        printf("i : %d\n",i);

        i=fork();
        printf("\n");

        if(i==0)
        {

                printf("Child has started\n\n");
                printf("child printing first time \n");

                printf("getpid : %d getppid : %d \n",getpid(),getppid());
                sleep(5);
                printf("\nchild printing second time \n");
                printf("getpid : %d getppid : %d \n",getpid(),getppid());
        }
        else
        {
                printf("parent has started\n");
                printf("getpid : %d  getppid : %d \n",getpid(),getppid());
                printf("\n");

        }

        printf("Hi after fork i : %d\n",i);

        return 0;


}

Output:

[04mca8@LINTEL pp]$ ./a.out hello before fork i : 134514088

Child has started

child printing first time getpid : 8354 getppid : 8353

parent has started getpid : 8353 getppid : 5656

Hi after fork i : 8354 [04mca8@LINTEL pp]$ child printing second time getpid : 8354 getppid : 1 Hi after fork i : 0

关于c - 在 fork() 之后打印子编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461808/

相关文章:

c - 一个未初始化的变量可能有一个未定义的值,但那个未定义的值是否具有相同的数据类型?

c - 确定恰好具有 4 个节点的子树数量的最佳方法是什么?

c - 密码提示

c - 开发非 x86 操作系统

c - 事件和信号量的区别

c - c中计算机计算能力的上界

c - 如何将返回的函数值分配给 const 全局变量

linux - 合并不同目录下的两个文件

c++ - 结合大型 C 和 C++ 程序

linux - Unix 环境变量未设置为远程执行