0% found this document useful (0 votes)
20 views

Processes and Threads

Uploaded by

jet.fire.ch.021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Processes and Threads

Uploaded by

jet.fire.ch.021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Advance C Process 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.

Key points about processes:

• 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.

Key points about threads:

• 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.

Difference between Processes and Threads:

• 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

Aspect Processes 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.

3. History and Implementations:

Time Period Development


1950s - 1960s - Computers were single-tasking, running one program at a time.
- Emergence of the concept of a "process" representing an executing instance of a program.
1970s - Multi-programming systems allowed multiple programs to be loaded into memory
simultaneously.
- Time-sharing systems enabled multiple users to interact with the computer concurrently.
1980s - Threads emerged as lightweight units of execution within a process.
- Threads enabled concurrent execution within a single program, improving resource utilization.
1990s - Multi-core processors became prevalent, containing multiple processing units on a single chip.
- Threads became essential for leveraging parallelism across multiple cores, enhancing
performance.
Today - Processes and threads continue to evolve alongside advancements in hardware and software.
- They remain fundamental constructs in concurrent and parallel programming, facilitating
efficient utilization of modern computing resources.

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.

Methods in System Calls

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.

Syntax(Common for POSIX & Windows):

int system(const char *command);

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.

Syntax(Common for POSIX & Windows): char *getenv(const char *name);

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

3. setenv() Function (POSIX):

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:

int setenv(const char *name, const char *value, int overwrite);

• 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;
}

SetEnvironmentVariable() Function (Windows):

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

5. Processes in Unix Way:

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:

• fork() creates a new process by duplicating the calling process.


• The child process gets a unique process ID and a copy of the parent's address space.
• Returns:
o 0 to the child process.
o The child's PID to the parent process.
o -1 if an error occurs.

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:

void exit(int status);

Behavior:

• Terminates the calling process.


• status is returned to the parent process or the system.
• Performs cleanup tasks like flushing buffers and calling functions registered with atexit().

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:

• execl(), execle(), execlp(), execv(), execve(), execvp(), etc.

Syntax:

int execl(const char *path, const char *arg, ...);


int execv(const char *path, char *const argv[]);

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);

// If execv returns, it must have failed.


perror("execv");
exit(EXIT_FAILURE);
}

4. wait() and waitpid()

Definition:

wait() and waitpid() are used by a process to wait for state changes in a child process (such as termination).

Syntax:

pid_t wait(int *status);


pid_t waitpid(pid_t pid, int *status, int options);

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;
}

6. Processes in MS Windows Way:

CreateProcess() is the primary function for creating new processes in Windows.

• 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
);

• It creates a new process and its primary thread.


• Parameters include the application name, command line, process attributes, and more.
• Returns a non-zero value on success and zero on failure.

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));

// Start Microsoft Word.


success = CreateProcess(
"C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE",
// Path to Microsoft Word executable
NULL, // Command line (optional)
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure
);

if (!success) {
printf("CreateProcess failed (%d).\n", GetLastError());
return 1;
}

// Wait until Microsoft Word process exits.


WaitForSingleObject(pi.hProcess, INFINITE);

https://orion021.github.io/krishnan_t/ 8 | 😁 👻 ✌️ 😎
Advance C – Process and Threads

printf("Microsoft Word process completed.\n");

// Close process and thread handles.


CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

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.

• Learn about functions like pthread_create(), pthread_join(), and pthread_exit().

8. Threads in MS Windows:

Thread Management 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:

1. CreateThread():This function creates a new thread within a process.


o Syntax:

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;

// Create the thread


hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunction, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier

// Check if the thread is created successfully


if (hThread == NULL) {
printf("Error creating thread\n");
return 1;
}

// Wait until the thread terminates


WaitForSingleObject(hThread, INFINITE);

// Close the thread handle


CloseHandle(hThread);

printf("Thread execution completed\n");


return 0;
}

https://orion021.github.io/krishnan_t/ 10 | 😁 👻 ✌️ 😎
Advance C – Process and Threads

9. C11 Threads:

• Learn about the threading support introduced in the C11 standard.

• 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 | 😁 👻 ✌️ 😎

You might also like