简体   繁体   English

带有 fork() 的 c 程序的奇怪行为

[英]Odd behavior of a c program with fork()

In my homework I should explain what is happening in the following code:在我的作业中,我应该解释以下代码中发生的事情:

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

int main(){
    int x = 1; 
    if(fork() == 0){// child
        printf("printf1: x=%d\n", ++x);// add then print
    }
    printf("printf2: x=%d\n", --x);
    exit(0);  
}

It's pretty straightforward and easy to understand.这非常简单易懂。 Most of the time I get the following output:大多数时候我得到以下output:

printf2: x=0
printf1: x=2
printf2: x=1

This means that the parent process was completed before the child and the child became a zombie process.这意味着父进程在子进程之前完成,子进程成为僵尸进程。 But sometimes I get the following output:但有时我会得到以下 output:

printf1: x=2
printf2: x=1

After printing that the program freezes (It does not print anything and does not stop).打印后程序冻结(它不打印任何内容,也不会停止)。 I am running the program on Ubuntu.我在 Ubuntu 上运行程序。 Any explanation will be appreciated.任何解释将不胜感激。

You have 3 processes writing to your terminal: parent, child and the shell interpreter.您有 3 个进程写入您的终端:父进程、子进程和 shell 解释器。 The parent process and the shell have "syncronized" output, but the child process may interleave its output with either of those.父进程和 shell 具有“同步”output,但子进程可以将其 output 与其中任何一个交错。 What you may perceive as a hanged process, may actually only be mangled output.您可能认为是挂起的进程,实际上可能只是被损坏的 output。

When you think it has hanged, you may try to enter a command and press enter...当您认为它已经挂起时,您可以尝试输入命令并按回车...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM