In: Computer Science
Here is the example of how to use child threads in a client.cpp to send info to a server.cpp and how a server.cpp uses child processes to send back info to the client.
#include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <stdio.h> int main() { int status; pid_t pid = fork(); // Child process will sleep for 10 second if(pid == 0) { execl("/usr/bin/sleep", "/usr/bin/sleep", 10, NULL); } // Parent process will wait for child process to terminate // Then, it will report the exit status of the child process else { waitpid(pid, &status;, 0); printf("status = %d\n", status); // print out -> status = 65280 } }
Here are the some keyword used in the program which have meanings as follows like..
1. Execl() -- It is used here for to execute the sleep program.
2. Waitpid()-- It is used here for wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be:
In the case of a terminated child, performing a wait allows the
system to release the resources associated with the child.
If a wait is not performed, then the terminated child
remains in a zombie state.
If a child has already changed state, then it returns immediately. Otherwise it block until either a child changes state or a signal handler interrupts the call.