Question: Linux question with c programs 2) Run cloneThread Your output should be (except for pids): The variable was: 9 Part after clone has pid 11051

Linux question with c programs

2) Run cloneThread Your output should be (except for pids): The variable was: 9 Part after clone has pid 11051 I am 11052 and my parent is 11051 The variable is now: 42 File Read Error: Bad file descriptor

Explain why the file closure and the variable modification ARE recognized (variable has new value, and file closed).

cloneThread.c

/* In this program, we make a child "thread" by using clone and having both parent and child share memory and file space by using flags CLONE_VM and CLONE_FILES

Note: would have made a "heavyweight process" if we had used clone, but not set any flags (which is what fork does). The child would get a copy of parents memory, file descs, etc, but any changes in child would be only for the child

For making a child process see cloneProcess.c */

#define _GNU_SOURCE //for Ubuntu #include #include #include #include #include #include #include

int variable, fd;

int do_something() { variable = 42; close(fd); printf("I am %d and my parent is %d ", getpid(), getppid()); _exit(0); }

int main(int argc, char *argv[]) { const int STACK_SIZE = 65536; //note stack grows down char *stack; char *stackTop; char tempch; int cret;

stack = malloc(STACK_SIZE); if (stack == NULL) { perror("malloc"); exit(1); } stackTop = stack + STACK_SIZE; /* Assume stack grows downward */

variable = 9; fd = open("test.file", O_RDONLY); if (fd == -1) { fprintf(stderr, "To run this, you need a file named test.file in this directory!! "); exit(2); } printf("The variable was: %d ", variable);

cret=clone(do_something, stackTop, CLONE_VM|CLONE_FILES, NULL); if (cret==-1) {perror("clone"); exit(0); } //parent keeps going here printf("Part after clone has pid %d ",getpid()); sleep(1);

printf("The variable is now: %d ", variable); if (read(fd, &tempch, 1) < 1) { perror("File Read Error"); exit(1); } printf("Read from the file. Got: %s ", &tempch); return 0; }

//from //linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/052/5211/5211l1.html

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!