Reason for segmentation failure

I wrote a program using the clone () system call with a set of CLONE_VM and CLONE_FILES. I canโ€™t understand why the output shows a segmentation error. Can someone please correct my code and tell me the reason for the same.

#include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<sched.h> #include<stdlib.h> int variable, fd; int do_something() { // sleep(100); variable = 42; close(fd); _exit(0); } int main(int argc, char *argv[]) { void **child_stack; char tempch; variable = 9; fd = open("test.file", O_RDONLY); child_stack = (void **) malloc(16384); printf("The variable was %d\n", variable); clone(do_something, child_stack, CLONE_VM|CLONE_FILES, NULL); // sleep(100); printf("The variable is now %d\n", variable); if (read(fd, &tempch, 1) < 1) { perror("File Read Error"); exit(1); } printf("We could read from the file\n"); return 0; } 
+4
source share
2 answers

You need to know which direction stack is growing on your processor, and you need to know which end of the stack you should go to clone () for.

From man clone :

 Stacks grow downwards on all processors that run Linux (except the HP PA processors), so child_stack usually points to the topmost address of the memory space set up for the child stack. 

You do not miss the highest address, you pass the lowest address, and you do not (I guess) on HP-PA.

Fix:

  child_stack = (void **) malloc(16384) + 16384 / sizeof(*child_stack); 

PS I am amazed at the number of obviously wrong non-answers here.

  • No, closing an invalid file descriptor does not crash on any UNIX and Linux system exists.
  • No, void* vs. void** has nothing to do with this problem.
  • No, you do not need to take the address do_something, the compiler will do this automatically for you.

And finally, yes: calling close , _exit or any other libc procedure in the clone()d thread is potentially unsafe, although this does not cause a problem here.

+4
source

The fix path is that the child stack is actually on the stack. ie

char child_stack [16384];

I suspect that the stack pointer cannot point to a data segment or sth like this ...

And even then .. it works with -g .. but it crashes with -O !!!

-1
source

Source: https://habr.com/ru/post/1343109/


All Articles