0

主要代码如下:

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

输出如下:

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

问题是:为什么“aimager@cong-Ubuntu:/mnt/LinuxDatum/WorkSpace/Ubuntu$”在前面输出

4

1 回答 1

1

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)

于 2013-10-10T03:20:51.987 回答