c - "if (pid = fork() > 0)"- 为什么 fork() 返回 pid 1 (systemd)?

标签 c linux multiprocessing fork

在我的 main() 函数中,我在循环中调用了 fork(),成功创建了三个子进程。

代码类似于:

    int pid = -1;
    int num_processes = 3;
    int pid_array[num_processes];
    for (i = 0; i < num_processes; i++)
    {
        if (pid = fork() > 0)
        {
            pid_array[i] = pid;
            //do parent stuff
        }
    }

我可以通过“ps -ef”看到子进程正在创建,并且列出了父进程的正确 pid,而且这些进程正在运行并正常运行。

问题是我需要将子进程 pid 存储在父进程的 pid_array 中,但它们都存储为 1。在 gdb 中,我看到 fork() 每次都返回 1,而不是像我想的那样返回子进程 pid预计。

所以它返回 1,这是 systemd 的 pid。为什么它返回pid 1(systemd)而不是成功创建的子进程的pid?

为了更好地衡量,我的系统上 fork 的手册页:

   RETURN VALUE
           On success, the PID of the child process is returned  in  the  parent,  and  0  is
           returned in the child.  On failure, -1 is returned in the parent, no child process
           is created, and errno is set appropriately.

最佳答案

pid = fork() > 0

fork返回值大于0,因此,fork()返回值确实大于0,除非fork sys_call失败,pid被赋值1。

关于c - "if (pid = fork() > 0)"- 为什么 fork() 返回 pid 1 (systemd)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882573/

相关文章:

linux - 如何禁用 Qt 在 Linux 上捕获小部件焦点导航箭头键的行为

linux - 通过 Wine 在 Linux 上运行基于 COM/DCOM 的应用程序

python - 如何在函数内初始化并行独立进程?

python - 在 Python 多处理中将 Pool.map 与共享内存数组结合起来

c - C中的内存替换?

linux - Bash 脚本记录平均 ping 时间,一天每 20 秒一次

c - 在 C 中实现一个字符串转换表

c - 在核心之间共享数据的最有效方式

c - if方法中为什么不清屏(仅限C语言)

c - 实际在 C 中定义的函数的 undefined reference 错误