Reputation: 4888
I have some experience in using threads and processes in Windows.
May someone explain, is there any mapping possible the threads and processes in windows to the same in Linux?
That means, Threads in Windows == Threads in Linux? -> Makes any sense? Process in Windows == Process in Linus? -> Makes any sense?
If same, I have CreateThread() and CreateProcess() calls in windows, what are the equivalent calls in linux?
I have read some posts in SO but most of them haven't cleared my doubts.So thought to start a new post.
It would be nice If I get some explanation with some simple examples(C programming).
Upvotes: 6
Views: 7242
Reputation: 62439
Well, there are equivalent calls for your purpose in Linux, but they work a little different, at least for the process mechanism.
For threads, you can use pthread_create
. It works in a very similar fashion to CreateThread
, except some parameters are different. Should be very easy to use. Here's a good tutorial: https://computing.llnl.gov/tutorials/pthreads/
Emulating CreateProcess
in order to start an external process is not so straightforward. You will need the famous fork/exec
combo. First, you need to call fork
inside the main process to spawn a child process. This child is created by duplicating the initial process. You can then control the flow by checking the value returned by fork
:
int rv = fork(); // new process was spawned here. The following code is executed // by both processes. if(rv == 0) { // we are in the child process } else { // we are in the parent }
Basically rv
will be 0 for the child and the pid of the child for the parent. I hope I haven't lost you so far. :)
Moving on, you will need a call to one of the exec
family of functions to start an external process:
int rv = fork(); // new process was spawned here. The following code is executed // by both processes. if(rv == 0) { execl("/bin/ls", "ls", NULL); // start the ls process } else { // we are in the parent }
In the above example, I am starting the /bin/ls
external process, which prints the contents of the current folder.
Here's a simple full example: http://flinflon.brandonu.ca/dueck/2001/62306/Processes/Unix%20Examples.htm
Now you may be wondering why you need to call fork
in the first place and why execl
is not enough. This is because after the program invoked by execl
terminates, the current process is also terminated, and you don't want that to happen in the main process.
Upvotes: 8