我从一条指令中读取了这样的代码段
#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
我对孩子的pid感到困惑
if ((pid = fork()) < 0)
该pid设置为0,但在输出中,其pid为7310。
那怎么可能呢?
这里的pid只是一个数字而不是一个过程吗?