The key points are;
- Children processes are created with a call to fork, Fork returns:
- A number less than 0(the Error code) on an error.
- A number equal to 0 in the thread.
- A number greater than to 0(the childs pid) in the main process.
- A call to getpid() will return the pid of the child or parent process.
- Keep in might the differences between a thread and process. The fundamental difference is that a thread shares all regions of memory except the stack where as a process shares none. In general memory is copied over the the child process as needed by the kernel.
//complie with; g++ fork.cpp #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <time.h> struct BaseA { pid_t pid; int number; }; //The thread core... void child_worker(BaseA* data) { data->pid = getpid(); for(int i = 0; i < 10; i++) { printf("Child %d @ %d \n", data->pid, data->number++); sleep(rand()%3000/1000); } printf("Child %d DONE!\n", data->pid); exit(0); } int main() { srand(time(NULL)); pid_t childPid; BaseA data; //setup the process data.number = 1; // create the threads childPid = fork(); if (childPid >= 0) // fork ok if (childPid == 0) // Am I the kid child_worker(&data); childPid = fork(); if (childPid >= 0) // fork ok if (childPid == 0) // Am I the kid child_worker(&data); //wait for all kids to complete wait(NULL); wait(NULL); printf("Parent %d DONE!\n", data.number); exit(0); }
No comments:
Post a Comment