/**************************************/ /* */ /* Prof. Dr. Carsten Vogt */ /* TH Koeln, Fakultaet IME */ /* http://www.nt.th-koeln.de/vogt */ /* */ /* Linux-C-Schnittstelle: */ /* Thread-Erzeugung mit clone() */ /* */ /**************************************/ #define _GNU_SOURCE #include #include #include #include int a; int sohn_funktion() { printf("Sohn-PID: %d\n\n",getpid()); a = 10000; printf(" Sohn hat a auf %d gesetzt\n\n",a); exit(0); } int main(int argc, char *argv[]) { void *sohn_stack; sohn_stack = (void *) malloc(16384); if (sohn_stack == -1) { printf("malloc fehlgeschlagen\n"); exit(-1); } printf("Vater-PID: %d\n\n",getpid()); /* Erster Aufruf von clone() */ printf("Erste Runde:\n\n"); a = 1; printf(" a im Vater: %d\n\n", a); printf(" Aufruf des Sohns: clone(...,...,0,...)\n"); printf(" Vater und Sohn haben also getrennte Speicherbereiche\n\n"); clone(sohn_funktion, sohn_stack+16383, 0, 0); // Wikipedia - clone(): child_stack argument is a pointer to a memory space to be used as the stack for the new thread // (which must be malloc'ed before that; on most architectures stack grows down, so the pointer should point // at the end of the space) sleep(1); printf(" a im Vater: %d\n\n", a); sleep(1); /* Zweiter Aufruf von clone() */ printf("Zweite Runde:\n\n"); a = 1; printf(" a im Vater: %d\n\n", a); sohn_stack = (void **) malloc(16384); /* CLONE_VM im dritten Parameter = Vater und Sohn benutzen jeweils eigene Speicherbereiche */ printf(" Aufruf des Sohns: clone(...,...,CLONE_VM,...)\n"); printf(" Vater und Sohn haben also einen gemeinsamen Speicherbereich\n\n"); clone(sohn_funktion, sohn_stack+16383, CLONE_VM, 0); sleep(1); printf(" a im Vater: %d\n\n", a); return 0; }