c - 系统调用基础知识以及该程序的内容

标签 c linux unix fork

<分区>

我想知道这个程序的输出是关于系统调用的。我试图理解,但这很难。

int main (void) {
  pid_t pid;
  pid = fork(); 
  if (pid > 0) {
    int i; 
    for (i = 0; i < 5; i++) { 
      printf(" I AM VU : %d\n", i);
      sleep(1);
    }
    exit(0);
  } 
  else if (pid == 0) {
    int j;
    for (j = 0; j < 5; j++) {
      printf(" I have no child: %d\n", j);
      sleep(1);
    }
    exit(0);
  } else {
    fprintf(stderr, "can't fork, error %d\n", errno);
    exit (EXIT_FAILURE);
  }
}

最佳答案

编译运行这段代码后,父级会输出如下内容:

 I AM VU : 0
 I AM VU : 1
 I AM VU : 2
 I AM VU : 3
 I AM VU : 4 

单子(monad)会输出类似这样的东西:

 I have no child: 0
 I have no child: 1
 I have no child: 2
 I have no child: 3
 I have no child: 4

child 的五行几乎肯定会与 parent 的输出行混淆,所以你会在屏幕上看到这样的东西:

I AM VU : 0
I have no child: 0
I AM VU : 1
I have no child: 1
I have no child: 2
I have no child: 3
I AM VU : 2
I have no child: 4
I AM VU : 3
I AM VU : 4

如果 fork() 失败,程序将输出如下内容:

can't fork xx where xx is errno.

注意 我不认为fork( )系统 调用,而是 调用em> 功能。实践和效果差异不大,但仍然如此。

关于c - 系统调用基础知识以及该程序的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5692962/

相关文章:

c - 使用 Pthreads 进行并行编程

c++ - 为每个连接手动分配端口号

c - System V AMD64 ABI 浮点可变参数顺序

OpenSUSE 中的 Java 开发

c - 当我试图编译它时,Xcode 关闭项目

c - request_mem_region() 实际上做了什么以及何时需要?

c - 按头和节点制作链表

c - 一行内的预处理器指令 if

linux - 如何使用shell脚本创建多个目录

linux - 管道将输入拆分为命令