c - fork系统调用

标签 c fork

我尝试在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 ?!

另一个问题,这个输出总是一样吗?!或者有时可以颠倒?!

亲切的问候

最佳答案

fork(2):

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/

相关文章:

c - 试图找出为什么子进程比应有的时间更早终止

c - 在函数中调用 fork() 后主进程不打印

c - 如何限制子线程或子进程以限制在 C 中 fork

c - 修改 ALSA arecord 函数以将音频电平输出到 Raspberry Pi 3 RGB LED

c - 为什么 strstr() 搜索空字符串总是返回 true?

c - 为什么 printf 函数在数字顺序与格式不对应的情况下按顺序打印结果?

c - PKCS11,对象 PIN

c - CPU 与使用 malloc 的 Wall time 测量值的奇怪差异

c - wait() 等待子进程崩溃

multithreading - Perl: fork 和填充父数组