AImager
AImager

Reputation: 55

About process and sleep()

I have write a program by C and run it in Ubuntu,the main code is follow:

int main(){    
    pid_t pid=fork();
    if(pid==0){
        printf("d");
        exit(0);
    }
    else{
        printf("a");
        sleep(4);
    }
}

The question is: why the code sleep(4); run before printf("a");

hope someone can give me a answer,thanks!

Upvotes: 1

Views: 85

Answers (3)

paulsm4
paulsm4

Reputation: 121881

Q: why the code sleep(4) run before printf("a")?

A: printf("a") actually runs BEFORE "sleep(4)", just like you see in the code.

However, it doesn't DISPLAY immediately.

The issue is "buffering".

Look here for more details:

SUGGESTED ALTERNATIVE:

pid_t pid=fork();
if(pid==0){
    fprintf(stderr, "d");
    exit(0);
}
else{
    fprintf(stderr, "a");
    sleep(4);
}

The reason is that "stderr" is unbuffered: you'll see the output immediately.

Alternatives to using stderr include calling fflush(stdout) or modifying the stream.

Upvotes: 3

Ben
Ben

Reputation: 693

It's not, but it may appear that way. printf puts its output into a buffer that probably only gets flushed after the sleep runs. Try putting a call to fflush(stdout) after the printf, but before the call to sleep.

Upvotes: 2

Alexander L. Belikoff
Alexander L. Belikoff

Reputation: 5721

It is not. Most probably, printf() buffered its output until a chance to output the buffer (in your case, when the process terminated).

Upvotes: 4

Related Questions