Processes and Threads
Processes and Threads
- Krishnan
1. Processes:
A process is an executing instance of a program. When you run a program, the operating system creates a process
to execute that program. Each process has its own memory space, which includes the code, data, stack, and heap
segments. Processes are isolated from each other, meaning they cannot directly access each other's memory.
• Isolation: Processes are isolated from each other, meaning they cannot directly access each other's memory. This
isolation provides security and stability to the system.
• Resource Allocation: Each process has its own set of system resources, such as CPU time, memory, file descriptors,
and I/O devices.
• Independence: Processes can run independently of each other. They can execute different parts of the program
simultaneously, which is useful for multitasking and parallel processing.
• Creation and Termination: Processes are created and terminated by the operating system. When a program starts,
the operating system creates a new process for it. When the program finishes execution, the process is terminated.
2. Threads:
A thread is a lightweight process within a process. Threads share the same memory space and system resources
as their parent process, but they have their own execution flow. This allows multiple threads within a process to execute
concurrently.
• Concurrency: Threads allow multiple tasks to execute concurrently within a single process. This can lead to
improved performance and responsiveness in applications.
• Shared Memory: Threads within the same process share the same memory space, including global variables, heap
memory, and static data. This allows threads to communicate and synchronize with each other efficiently.
• Creation and Scheduling: Threads are created and scheduled by the operating system's thread scheduler. The
scheduler determines the order in which threads are executed on the CPU.
• Lightweight: Threads are lightweight compared to processes because they share resources with the parent
process. Creating and switching between threads is faster and requires less overhead than creating and switching
between processes.
• Isolation: Processes are fully isolated from each other, whereas threads within the same process share the same
memory space and resources.
• Resource Usage: Each process has its own set of system resources, whereas threads within the same process share
the resources of the parent process.
• Overhead: Creating and switching between processes is more expensive in terms of overhead compared to
creating and switching between threads.
https://orion021.github.io/krishnan_t/ 1 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
Process vs Threads
Creation Created by the operating system. Created within a process by the application or the
OS.
Memory Space Each process has its own memory Threads within the same process share the same
space. memory space.
Isolation Processes are fully isolated from each Threads within the same process share resources.
other.
Communication Inter-process communication is more Threads communicate more easily via shared
complex. memory.
Scheduling Scheduled independently by the OS Scheduled within the context of the parent
scheduler. process.
Switching Overhead Switching between processes is more Switching between threads is less expensive.
expensive.
Resource Usage Each process has its own set of Threads within a process share resources.
resources.
Concurrency Processes do not inherently support Threads support concurrency within a process.
concurrency.
Dependency Processes can run independently of Threads within the same process depend on each
each other. other.
Creation Overhead Creating a process involves more Creating a thread involves less overhead.
overhead.
Communication Inter-process communication may have Inter-thread communication has less overhead.
Overhead overhead.
https://orion021.github.io/krishnan_t/ 2 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
4. System Calls:
In C programming, system calls are functions provided by the operating system kernel that can be called from user-
space programs to request services from the operating system. These services typically involve interacting with
hardware, managing processes, accessing files, and performing various system-related tasks.
1. system() Function:
The system() function is used to execute shell commands from within a C program, both in POSIX-compliant
systems like Unix/Linux and in Windows environments.
Example (POSIX):
#include <stdlib.h>
int main() {
// Execute the 'ls -l' command (Unix/Linux)
int status = system("ls -l");
return status;
}
Example (Windows):
#include <stdlib.h>
int main() {
// Execute the 'dir' command (Windows)
int status = system("dir");
return status;
}
2. getenv() Function:
In both POSIX-compliant systems (like Unix/Linux) and Windows, the getenv() function is used to retrieve the
value of an environment variable.
Example (POSIX):
#include <stdlib.h>
#include <stdio.h>
int main() {
// Retrieve the value of the "PATH" environment variable (Unix/Linux and Windows)
char *path = getenv("PATH");
if (path != NULL) {
printf("The PATH variable is: %s\n", path);
} else {
printf("The PATH variable is not set\n");
}
return 0;
}
https://orion021.github.io/krishnan_t/ 3 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
The setenv() function is used to set the value of an environment variable or create a new one if it doesn't exist
in POSIX-compliant systems.
Syntax:
• name: A string containing the name of the environment variable to be set or created.
• value: A string containing the value to be assigned to the environment variable.
• overwrite: An integer flag indicating whether to overwrite an existing variable (non-zero) or not (zero).
• Returns:
o If the operation is successful, setenv() returns 0.
o If an error occurs, setenv() returns -1.
Example:
#include <stdlib.h>
int main() {
/*Set the value of the "PATH" environment
variable to include "/usr/local/bin"*/
setenv("PATH", "/usr/local/bin", 1);
return 0;
}
The SetEnvironmentVariable() function is used to set the value of an environment variable in Windows systems.
Syntax:
BOOL SetEnvironmentVariable(
LPCTSTR lpName,
LPCTSTR lpValue
);
• lpName: A pointer to a null-terminated string that specifies the name of the environment variable.
• lpValue: A pointer to a null-terminated string that specifies the new value of the variable.
• Returns:
o TRUE if the function succeeds.
o FALSE if the function fails.
Example:
#include <Windows.h>
int main() {
// Set the value of the "PATH" environment variable to include "C:\Program Files"
SetEnvironmentVariable("PATH", "C:\\Program Files");
return 0;
}
https://orion021.github.io/krishnan_t/ 4 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
1. fork()
fork() is used to create a new process by duplicating the existing process. The new process is called the child
process, and the existing one is the parent process.
Syntax:
pid_t fork(void);
Behavior:
Example:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("This is the child process.\n");
} else if (pid > 0) {
// Parent process
printf("This is the parent process.\n");
} else {
// Fork failed
perror("fork");
}
return 0;
}
2. exit()
exit() terminates a process, closing all file descriptors, and performs cleanup.
Syntax:
Behavior:
https://orion021.github.io/krishnan_t/ 5 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Exiting program.\n");
exit(0); // Success
}
3. execxx()
The exec family of functions replaces the current process image with a new process image.
Common Variants:
Syntax:
Behavior:
• The new process image is loaded from an executable file specified by the path.
• The exec function does not return on success because the new process image replaces the current process
image.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
char *args[] = {"/bin/ls", "-l", NULL};
execv("/bin/ls", args);
Definition:
wait() and waitpid() are used by a process to wait for state changes in a child process (such as termination).
Syntax:
https://orion021.github.io/krishnan_t/ 6 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
Behavior:
• wait() suspends execution of the calling process until one of its children terminates.
• waitpid() can be used to wait for a specific child process or for any child process with more control.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("Child process.\n");
exit(0); // Terminate child process
} else if (pid > 0) {
// Parent process
int status;
waitpid(pid, &status, 0); // Wait for the child process to terminate
printf("Child process terminated.\n");
} else {
// Fork failed
perror("fork");
}
return 0;
}
• Syntax:
BOOL CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
https://orion021.github.io/krishnan_t/ 7 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
WaitForSingleObject() Function:
After creating a process, you often need to wait for it to finish executing. WaitForSingleObject() allows a
thread to wait until the specified object is in the signaled state or the time-out interval elapses.
• Syntax:
DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
• hHandle is a handle to the object to wait for, which in this case would be the process handle returned by
CreateProcess().
• dwMilliseconds specifies the time-out interval in milliseconds.
Example Usage:
• Here's a basic example of how you might use CreateProcess() and WaitForSingleObject() to run an external
executable and wait for it to complete:
#include <windows.h>
#include <stdio.h>
int main() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL success;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (!success) {
printf("CreateProcess failed (%d).\n", GetLastError());
return 1;
}
https://orion021.github.io/krishnan_t/ 8 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
return 0;
}
• In this example, WINWORD.exe is a placeholder for the executable you want to run.
Process Termination:
• Once the process has completed, you should close the handles to the process and its primary thread
using CloseHandle() to free system resources.
7. Threads in Unix/Linux:
• Study POSIX threads (pthread) for creating and managing threads in Unix/Linux environments.
8. Threads in MS Windows:
Definition:
Threads in MS Windows: In Windows, threads are the smallest unit of execution within a process. Each thread
in a process shares the process's resources, but operates independently. Windows provides a set of API
functions to create, manage, and synchronize threads.
Key Functions:
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
o Parameters:
▪ lpThreadAttributes: A pointer to a SECURITY_ATTRIBUTES structure that determines
whether the returned handle can be inherited by child processes. If NULL, the handle cannot be
inherited.
▪ dwStackSize: The initial size of the stack, in bytes. If this parameter is zero, the new thread uses
the default size.
▪ lpStartAddress: A pointer to the application-defined function to be executed by the thread.
▪ lpParameter: A pointer to a variable to be passed to the thread.
▪ dwCreationFlags: Flags that control the creation of the thread.
▪ lpThreadId: A pointer to a variable that receives the thread identifier.
https://orion021.github.io/krishnan_t/ 9 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
2. WaitForSingleObject():
This function waits until the specified object is in the signaled state or the time-out interval elapses.
o Syntax:
DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
o Parameters:
▪ hHandle: A handle to the object.
▪ dwMilliseconds: The time-out interval, in milliseconds.
Example:
#include <windows.h>
#include <stdio.h>
// Thread function
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
printf("Thread is running...\n");
return 0;
}
int main() {
HANDLE hThread;
DWORD dwThreadId;
https://orion021.github.io/krishnan_t/ 10 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
9. C11 Threads:
• Study the <threads.h> header and functions like thrd_create(), thrd_join(), and thrd_exit().
https://orion021.github.io/krishnan_t/ 11 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
https://orion021.github.io/krishnan_t/ 12 | 😁 👻 ✌️ 😎
Advance C – Process and Threads
https://orion021.github.io/krishnan_t/ 13 | 😁 👻 ✌️ 😎