0

Now, I have to write a c program and use clone() to make process do things asynchronous. I've read the manual of clone(); however, I still don't know how to make it work asynchronous. I use flags CLONE_THREAD, CLONE_VM and CLONE_SIGHAND and there's an infinite loop in parameter fn. I got segmentation fault(core dumped) first, then using gdb to debug. Then, I got Program received signal SIGSEGV, Segmentation fault. [Switching to LWP xxx]. I would like to make the processes switch successfully ?

Below is my code:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#define FIBER_STACK 1024*1024*8

int counter;
void * stack;
int do_something(){
    int i;
    while(1) {
        if (counter == 1000)
        {
            free(stack);
            exit(1);
        } else {
            counter++;
            i++;
        }
        printf("Process %d running total runs %d, and this process runs %d \n", getpid(), counter, i);
    }
}
int main() {
    void * stack;
    counter = 1;
    stack = malloc(FIBER_STACK);
    if(!stack) {
        printf("The stack failed\n");
        exit(0);
    }


    int i;
    for (i = 0; i < 26; i++)
    {
        clone(&do_something, (char *)stack + FIBER_STACK, CLONE_THREAD|CLONE_SIGHAND|CLONE_VM, 0); // CLONE_VFORK
    }
}

1 Answer 1

0

I got segmentation fault(core dumped) first

Of course. The point of handing the clone a stack is that it needs memory of its own. But you hand the same stack to 26 different processes! Also this is an "off by one" error:

(char *)stack + FIBER_STACK

Since if stack starts at 0x1 and FIBER_STACK is 5, it was allocated 5 addresses, 0x1, 0x2, 0x3, 0x4, 0x5. But 0x1 + 5 is 0x6. So you should subtract 1 from that.

Anyway, try something like:

#define NUM_PROC 8

int main() {
    void *stack[NUM_PROC];

    // --std=c99
    for (int i = 0; i < NUM_PROC; i++) {
        stack[i] = malloc(FIBER_STACK);
        if(!stack[i]) {
            printf("Out of memory?!\n");
            exit(0);
        }
    }            

    for (i = 0; i < NUM_PROC; i++) {
        clone(&do_something, (char *)stack[i] + FIBER_STACK - 1,

And it will run without faulting. But to keep the main process around you'll also want, e.g.:

     while (counter < 1000) sleep(1);

After the for() loop.

1
  • You save my time. Thanks a lot. It works for me now, though I still got my right answer. I will try it. Thank you again.
    – CYB
    May 20, 2014 at 15:13

Not the answer you're looking for? Browse other questions tagged .