Processes cont. #
Using fork
and execl
#
Consider this code
pid_t pid1, pid2; int status;
struct rusage usage;
if ((pid1=fork()))
{
printf("I am parent %d; child is %d\n",getpid(),pid1);
pid2=wait3(&status, 0, &usage);
printf("exit code for %d is %d\n", pid2, status);
}
else
{
execl("/bin/cat", "/bin/cat", "/csc/139/news/0001.txt", NULL);
printf("we should never get here!\n");
}
execl
loads cat
into the child’s memory space.
When this child cat
exits, it will never reach the subsequent printf
.
This outputs
I am parent ...; child is ...
cat of 0001.txt
exit code for ... is ...
Another output possibility could be
cat of 0001.txt
I am parent ...; child is ...
exit code for ... is ...
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
printf("A\n");
fork();
printf("B\n");
fork();
printf("C\n");
return 0;
}
Output
A
B
B
C
C
C
C
Threads #
So far, the processes that we have defined only have one thread of execution.
Idea: allow multiple threads of execution within the same process environment, to a large degree independent of each other.
Threads maintain the same code, data, and open files in memory. Each thread will have its own registers and stack. Threads will share the heap. The thread’s register and stack will swap when switching to another thread.
Multithreading #
PCB
- pid
- state
- pc
- registers
- open files
- …
TCB (Thread control block)
- state
- pc
- registers
The server will dispatch threads and then continue listening.
Benefits #
Multicore programming #
Concurrency
- supports more than one task making progress
- single processor / core, scheduler providing concurrency
- interleaves processes
Parallelism
- implies a system can perform more than one task simultaneously
User threads and kernel threads #
User processes
- can only run in user mode
- threads running in user mode are user processes
Kernel processes
- can only run in kernel mode
- threads running in kernel mode are kernel processes