c - 将子 pid 设置为 0 但输出其他

标签 c

我从一条指令中读到这样一段代码

#include "apue.h"

int globvar = 6; /* external variable in initialized data */
char buf[] = "a write to stdout\n";

int main(void)
{
    int var;
    pid_t pid; /* automatic variable on the stack */

    var = 88; if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
        err_sys("write error");
    printf("before fork\n"); /* we don’t flush stdout */

    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid == 0) { /* child */
        globvar++;         /* modify variables */
        var++;
    } else {
        sleep(2); /* parent */
    }

    printf("pid = %ld, glob = %d, var = %d, bufsize = %lu\n", (long)getpid(), globvar, var, sizeof(buf));

    exit(0);
}

运行它并获得输出

$ ./a.out
a write to stdout
before fork
pid = 7310, glob = 7, var = 89, bufsize = 19 #child’s variables were changed 
pid = 7309, glob = 6, var = 88, bufsize = 19 #parent’s copy was not changed

我对 child 的pid一头雾水

if ((pid = fork()) < 0)

pid 设置为 0,但在输出中它的 pid 是 7310。

怎么会这样?

这里的pid只是一个数字而不是一个进程吗?

最佳答案

fork()在子进程中返回 0,但在 printf 语句中,您使用 getpid() 打印 pid,这是子进程的实际 pid。

如果您在 printf 语句中使用了 pid 而不是 getpid()你会看到它打印 0。

关于c - 将子 pid 设置为 0 但输出其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53312123/

相关文章:

c - 内存分配的间隔

c - 内联函数 C 的函数指针

c# - 通过 Pinvoke 传递 C# 字符串

c++ - 结构的 Hexdump 没有输出正确的信息

c - 变量 'input' 周围的堆栈已损坏

c - malloc()/free() 的对齐限制

C - 用户输入数字的所有数字组合

c - 如何在 C 中声明和使用全局二维数组?

c - 一个用于查找变量长度的衬里

c - 如何在结构体数组中存储数字