在我的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,这些进程也正在运行并正常运行。
问题是我需要将子pids存储在父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.
答案 0 :(得分:3)
pid = fork() > 0
fork返回值大于0,因此,fork()返回值确实大于0,除非fork sys_call失败,pid得到赋值1.
答案 1 :(得分:3)
>
的{{3}}高于=
。
因此pid = fork() > 0
相当于pid = (fork() > 0)
。这将测试fork()
的结果是否大于零,并将测试结果分配给pid
。因此pid
将始终为零或一。
你想要的是(pid = fork()) > 0
。