简体   繁体   中英

About bash, process scheduling and printf()

The main code is follow:

int main(){
    pid_t pid=fork();
    if(pid==0){
        printf("a\n");
        exit(0);
    }
    else
        printf("b\n");
    return 0;
}

The output is follow:

b
aimager@cong-Ubuntu:/mnt/LinuxDatum/WorkSpace/Ubuntu$ a

The question is: Why "aimager@cong-Ubuntu:/mnt/LinuxDatum/WorkSpace/Ubuntu$" front output in a

You've executed process in foreground, so shell waits for its return before asking for next command. This process launches one more child process, which, for shell, is background. When initial process finishes, shell, unknowing anything about any subprocesses it never launched, asks you for next command with command prompt (in your case - it's username@hostname:/current/working/directory$), but after this background process decides to print some data. Prompt is already there, noone is going to remove it, so this data just appended here.

It only affects how you see things. Shell didn't got this data so it isn't added to command string, it just displayed that way. You could press return to force re-prompt if you like to see clear line.

You may see quite the same results with

$ (echo foo; echo bar) &

( & is command to shell to launch process in background - ask for next command without waiting for previous command to complete)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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