这个C代码做什么? [英] What does this C code do?

查看:69
本文介绍了这个C代码做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我做过很多其他类型的编程工作,但我对C编程确实很陌生.

I'm really new to C programming, although I have done quite a bit of other types of programming.

我想知道是否有人可以向我解释为什么该程序输出10.

I was wondering if someone could explain to me why this program outputs 10.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int value = 10;

int main()
{
    pid_t pid;

    pid = fork();
    if(pid == 0){
    value += 10;
    }
    else if(pid > 0){
        wait(NULL);
        printf("parent: value = %d\n", value); //Line A
        exit(0);
    }
}

我知道输出是"parent:value = 10".有人知道为什么吗?

I know the output is "parent: value = 10". Anyone know why?

谢谢!

推荐答案

关于fork():

  • 如果fork()返回负值, 子进程的创建是 不成功.
  • 如果fork()向新的返回零 创建的子进程.
  • 如果fork()返回正值,则 子进程的进程ID,以 父母.
  • If fork() returns a negative value, the creation of a child process was unsuccessful.
  • If fork() returns a zero to the newly created child process.
  • If fork() returns a positive value, the process ID of the child process, to the parent.

因此,在这种情况下,它必然会返回一个大于0&的数字.因此该值将保持为10&将被打印.

So in you case it bound to return a number greater than 0 & thus the value will remain 10 & will be printed.

这篇关于这个C代码做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆