Linux C

 

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

void main() {

    printf("main thread:%d\n", getpid());

    pid_t pid = fork();
    if (pid < 0) {
        printf("fork error\n");
    } else if (pid == 0) {
        printf("pid == 0 current pid:%d\n", getpid());
    } else if (pid > 0) {
        printf("pid > 0 pid:%d\n", getpid());
    }

    printf("where? pid:%d\n", getpid());
}

$gcc testfork.c -o haha

$./haha

main thread:6443
pid > 0 pid:6443
where? pid:6443
pid == 0 current pid:6444
where? pid:6444

fork后子线程和父线程是抢占机制,谁先运行,结果是不确定的。

 

posted @ 2015-04-13 19:03  牧 天  阅读(137)  评论(0)    收藏  举报