gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:20 26 4
gpt4 key购买 nike

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

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com