我尝试在c中执行以下代码:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
int main()
{
int pid;
pid = fork ();
printf ("%d \n", pid());
}
我得到以下结果:
17601
0
var pid 应该存储进程 id 的值,对吗?!
那么以下哪个是父级,哪个是子级 id ?! 更具体地说,我想知道 fork() 系统调用的返回值是什么?!为什么在这些进程之一中它是 0 ?!
另一个问题,这个输出总是一样吗?!或者有时可以颠倒?!
亲切的问候
最佳答案
RETURN VALUE
Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.
这里也许是一个更具说明性的示例:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
pid = fork ();
printf ("returned=%ld from %ld\n", (long)pid, (long)getpid());
}
这可能会给你输出,例如:
returned=22231 from 22229
returned=0 from 22231
请注意,fork()
返回 pid_t :
The implementation shall support one or more programming environments in which the widths of blksize_t, pid_t, size_t, ssize_t, and suseconds_t are no greater than the width of type long.
突出显示的部分意味着可以通过转换为 long
使用 stdio 打印 pid_t
,如我的示例中所示。
未指定是子级还是父级先运行。它们甚至可能同时运行,因此线路可以反转,并且在极少数情况下,您安装了信号处理程序并且它们被调用,甚至混合在一起(但这种情况很难触发)。
关于c - fork系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43307830/