C usual

 

#include<stdio.h>
#include<pthread.h>

void base() {
    //pritnf needs #include<stdio.h>
    printf("main\n");

    // pthread_t: unsigned long int
    pthread_t thread_id = pthread_self();
    printf("pthread_self(): %lu\n", thread_id);

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

void *thread_func(void *args) {
    printf("%s thread pid:%d\n", __func__, getpid());
    int *temp;
    temp = (int *) args;
    printf("%s *args:%d\n", __func__, *temp);
    printf("%s Parent thread id:%lu\n", __func__, pthread_self());

   return NULL;
}

void testfork() {
    //pit_t int
    pid_t pid = fork();

    if (pid == 0) {
        printf("Child thread pid:%d\n", getpid());
        printf("Child thread id:%lu\n", pthread_self());

        pthread_t thread_pid;
        int temp = 10;
        pthread_create(&thread_pid, NULL, &thread_func, &temp);
        pthread_join(thread_pid, NULL);
        printf("Child thread pthread_create() thread_pid:%lu\n", thread_pid);
    } else if (pid > 0) {
        printf("Parent thread pid:%d\n", getpid());
        printf("Parent thread id:%lu\n", pthread_self());
    } else {
        printf("fork error.");
    }

    printf("Thread pid:%d\n", getpid());
    printf("Thread id:%lu\n", pthread_self());
}

void main(int argc, char **argv) {
    base();
    printf("\n");

    testfork();
    printf("\n");
}

 

posted @ 2015-05-08 13:25  牧 天  阅读(137)  评论(0)    收藏  举报