c - C中的系统调用功能

标签 c system-calls

有人可以给我解释一下等待做什么,exit(0),exit(1),exit(2)等之间有什么区别。

这是我很困惑的代码。

int main() 
{ 
    if (fork()== 0) 
        printf("HC: hello from child\n"); 
    else
    { 
        printf("HP: hello from parent\n"); 
        wait(NULL); 
        printf("CT: child has terminated\n"); 
    } 

    printf("Bye\n"); 
    return 0; 
} 


输出量

HC: hello from child
Bye
HP: hello from parent
CT: child has terminated
     (or)
HP: hello from parent
HC: hello from child
CT: child has terminated    // this sentence does 
                            // not print before HC 
                            // because of wait.
Bye


这是来自geeksforgeeks的代码,因此转到if语句,如果if语句为true,则执行printf("HC: hello from child\n");,但是为什么又返回else语句并打印出printf("HP: hello from parent\n"); printf("CT: child has terminated\n");

最佳答案

您正在从单进程的角度看这件事。 fork()创建另一个与父进程完全相同的进程,只是有一个不同:克隆上fork()函数调用的结果是0,但是在父进程上,它是操作产生的PID。

因此,if (fork == 0)仅对孩子适用。

换句话说,两个分支同时跟随。

wait()部分是父级如何等待子级进程终止的方式。 NULL作为参数的意思大致是“不在乎哪个孩子,只是在乎哪个孩子”。通常,您将waitpid()与通过pid调用获得的fork()值一起使用,但这仅在可能涉及多个子进程的情况下才非常重要。

如果您不“收获”您的孩子,那么您的进程最终会变成僵尸,因此wait部分非常重要。

关于c - C中的系统调用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049780/

相关文章:

用于网络摄像头捕获的 C 程序

linux - 调用系统调用时的进程状态?

c - sys_readlink 失败 EFAULT - 备选方案

c - 系统调用在 C++ 中没有提供足够的内存

python - 系统调用和信号处理程序

c - 在 Linux 中 "which source"什么都不返回?

C - 哈希表键的链表

c - strlcpy 中的 'l' 是什么?

c++ - C 中的分数和整数分离

c - 如何在 Linux 资源中找到特定系统调用的定义?