在我的 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/