c - 理解Linux中的fork()

标签 c linux fork

我有以下代码

void main()
{

pid_t pid,pid1;

pid = fork();

if(pid==0)
{
  pid1= getpid();

  printf("\n Child A %d" ,pid);
  printf("\n Child B %d",pid1);
}
else
{

  pid1 = getpid();
  printf("\n Parent C %d:",pid); 
  printf("\nParent d %d:",pid1);

 }
}

我不明白为什么 B 和 C 的进程 ID 相同。任何人都可以帮助我吗?

最佳答案

pid1 = getpid();

它在子进程中运行,因此给出子进程 ID。

pid = fork();

这是从父进程发起的,但返回值对于父进程和子进程都是可用的。但是,它向父进程和子进程返回不同的值。直接来自fork man page :

the PID of the child process is returned in the parent, and 0 is returned in the child

因此,在两种情况(B 和 C)中,它都是子进程的 pid。

关于c - 理解Linux中的fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261821/

相关文章:

c - 在编写干净的 C 代码时利用 ARM 未对齐的内存访问

c++ - 用于全局内存的 Qt Linux 文件映射

linux - 在 as86/bin86 中包含二进制文件

c++ - 消失的子进程

c - 需要帮助调试简单的控制台游戏

更改控制终端

c - rsize_t 定义在哪个头文件中?

linux - 在 Go 中执行 Shell/Bash

unix - 在不同进程之间传递文件描述符的可移植方式

ruby - 如何在 Ruby 中控制子进程 stdin、stdout 等?