使用多线程进行分叉将使子进程中的堆栈内存无法访问

时间:2019-04-12 10:27:10

标签: linux multithreading fork

如果进程具有多线程派生,则将复制其他线程的堆栈内存,但无法访问。我认为这会浪费一些内存。 (因为未复制子线程)

//This code describes that the copied unreachable stack exists in the copied child process.
//The variable 'buf' has different values in both processes.

int sig;
int global;
int *ptr;
void proc()
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread_start, NULL);
    while (ptr == NULL);
    pid_t pid = fork();
    sig = 1;
    usleep(100000);
    if (pid)
    {
        printf("Process Response: %d, %p, %d\n", pid, ptr, *ptr);
        global = 1;
        int status;
        wait(&status);
    }
    else
    {
        printf("Process Response: %d, %p, %d\n", pid, ptr, *ptr);
        global = 2;
        exit(0);
    }
}

void *thread_start(void* data)
{
    int buf = 135;
    ptr = &buf;
    while (sig == 0);
    buf = 999;
    sig = 0;
    while (global == 0);
    printf("Thread Response: %d\n", global);
    return NULL;
}

此外,如果子线程在堆中分配了较大的内存,则内存的浪费将变得至关重要。 只是我不应该编写那样的程序吗?

0 个答案:

没有答案