线程的创建如何影响进程的ID

时间:2015-04-03 14:21:46

标签: c multithreading process pthreads

我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#define CHILD_NO 2
#define THREAD_NO 2
int counter = 0;
void *func(void *thread_no) {
    counter = counter + 1;
    printf("Func:  Proces ID = %d Parent process ID = %d Thread no = %d, Counter = %d \n", getpid(), getppid(), thread_no, counter);
    pthread_exit(NULL);
}

int main(void) {
    pthread_t threads[THREAD_NO];
    int childs[CHILD_NO];
    int rc, i, j;
    int f = 1;
    printf("Main: Proces ID = %d Parent process ID: %d\n", getpid(), getppid());
    for (i = 0; i < CHILD_NO; i++) {
        if (f > 0)
            f = fork();
        if (f == 0)
            break;
        else
            childs[i] = f;
    }
    if (f == 0) {
        printf("Child: Proces ID: %d Parent process ID: %d counter:%d\n" , getpid(), getppid(), counter);
        /*for(j = 0; j < THREAD_NO; j++)
            rc = pthread_create(&threads[j], NULL, func, (void *)j);*/
    }
    else{
        for (i = 0; i < CHILD_NO; i++)
            printf("Main: Child[%d] ID: %d created.\n", i, childs[i]);
        wait(NULL);
    }
    pthread_exit(0);
    return 0;
}

如果我将线程部分注释掉,我得到以下输出:

Main: Proces ID = 31138 Parent process ID: 28446
Child: Proces ID: 31139 Parent process ID: 31138 counter:0
Child: Proces ID: 31140 Parent process ID: 31138 counter:0
Main: Child[0] ID: 31139 created.
Main: Child[1] ID: 31140 created.

预期。父调用fork,子进程命中break并退出循环。这种情况发生了2次。所以我们有一个包含2个孩子的父进程。这就是全部。因此,如果父进程具有PID,则子进程将具有PID + 1而另一个将具有PID + 2。

如果我删除评论并运行代码,我会得到以下内容:

Main: Proces ID = 31664 Parent process ID: 28446
Child: Proces ID: 31665 Parent process ID: 31664 counter:0
Child: Proces ID: 31668 Parent process ID: 31664 counter:0
Main: Child[0] ID: 31665 created.
Main: Child[1] ID: 31668 created.
Func:  Proces ID = 31665 Parent process ID = 31664 Thread no = 1, Counter = 1 
Func:  Proces ID = 31665 Parent process ID = 31664 Thread no = 0, Counter = 2 
Func:  Proces ID = 31668 Parent process ID = 31664 Thread no = 1, Counter = 1 
Func:  Proces ID = 31668 Parent process ID = 31664 Thread no = 0, Counter = 2 

现在我了解线程的行为方式。不是他们的输出让我感到困惑。

子进程的PID如何以及为何相差3?进程的树层次结构不应该保持不变吗?

0 个答案:

没有答案