The Windows Processes and Threads 17

 

 

 

 

 

Fibers

 

A fiber is a unit of execution that must be manually scheduled by the application. Fibers run in the context of the threads that schedule them. Each thread can schedule multiple fibers. In general, fibers do not provide advantages over a well-designed multithreaded application. However, using fibers can make it easier to port applications that were designed to schedule their own threads. From a system standpoint, a fiber assumes the identity of the thread that runs it. For example, if a fiber accesses thread local storage (TLS), it is accessing the thread local storage of the thread that is running it. In addition, if a fiber calls the ExitThread() function, the thread that is running it exits. However, a fiber does not have all the same state information associated with it as that associated with a thread. The only state information maintained for a fiber is its stack, a subset of its registers, and the fiber data provided during fiber creation. The saved registers are the set of registers typically preserved across a function call. Fibers are not preemptively scheduled. You schedule a fiber by switching to it from another fiber. The system still schedules threads to run. When a thread running fibers is preempted, its currently running fiber is preempted but remains selected. The selected fiber runs when its thread runs.

Before scheduling the first fiber, call the ConvertThreadToFiber() function to create an area in which to save fiber state information. The calling thread is now the currently executing fiber. The stored state information for this fiber includes the fiber data passed as an argument to ConvertThreadToFiber(). The CreateFiber() function is used to create a new fiber from an existing fiber; the call requires the stack size, the starting address, and the fiber data. The starting address is typically a user-supplied function, called the fiber function, that takes one parameter (the fiber data) and does not return a value. If your fiber function returns, the thread running the fiber exits. To execute any fiber created with CreateFiber(), call the SwitchToFiber() function. You can call SwitchToFiber() with the address of a fiber created by a different thread. To do this, you must have the address returned to the other thread when it called CreateFiber and you must use proper synchronization. A fiber can retrieve the fiber data by calling the GetFiberData() macro. A fiber can retrieve the fiber address at any time by calling the GetCurrentFiber() macro.

 

Fiber Local Storage

 

A fiber can use fiber local storage (FLS) to create a unique copy of a variable for each fiber. If no fiber switching occurs, FLS acts exactly the same as thread local storage. The FLS functions ( FlsAlloc(), FlsFree(), FlsGetValue(), and FlsSetValue()) manipulate the FLS associated with the current thread. If the thread is executing a fiber and the fiber is switched, the FLS is also switched. To clean up the data associated with a fiber, call the DeleteFiber() function. This data includes the stack, a subset of the registers, and the fiber data. If the currently running fiber calls DeleteFiber(), its thread calls ExitThread() and terminates. However, if the selected fiber of a thread is deleted by a fiber running in another thread, the thread with the deleted fiber is likely to terminate abnormally because the fiber stack has been freed.

 

Creating Processes Program Example

 

The CreateProcess() function creates a new process, which runs independently of the creating process. However, for simplicity, the relationship is referred to as a parent-child relationship. The following code demonstrates how to create a process.

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

Creating Processes Program Example: Creating new Win32 C++ console application project in Visual C++ .NET

 

Then, add the source file and give it a suitable name.

 

Creating Processes Program Example: Adding new C++ source file for C++ source code to the existing C++ project

 

Next, add the following source code.

 

#include <windows.h>

#include <stdio.h>

#include <strsafe.h>

 

// Prototype

void ErrorHandler(LPTSTR lpszFunction);

 

// This wmain() is the main or parent process

int wmain(int argc, WCHAR *argv[])

{

    STARTUPINFO si;

    PROCESS_INFORMATION pi;

    DWORD Ret = 0;

     

    // The parent process and thread IDs

    wprintf(L"Parent process ID: %u\n", GetCurrentProcessId());

    wprintf(L"Parent thread ID: %u\n", GetCurrentThreadId());

 

    ZeroMemory(&si, sizeof(si));

    si.cb = sizeof(si);

    ZeroMemory(&pi, sizeof(pi));

 

    if(argc != 2)

    {

        wprintf(L"Usage: %s [cmdline]\n", argv[0]);

        wprintf(L"Example: %s \"C:\\WINDOWS\\system32\\ipconfig /all\"\n", argv[0]);

        return 1;

    }

 

    // Start the child process

    wprintf(L"Starting child process...\n");

    if( !CreateProcess( NULL,   // No module name (so use command line)

        argv[1],        // Command line

        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

    )

    {

        ErrorHandler(L"CreateProcess()");

        return 1;

    }

      else

      {

            wprintf(L"CreateProcess() - child process was created successfully!\n");

            // The child process and thread IDs

            wprintf(L"Child process ID: %u\n", pi.dwProcessId);

            wprintf(L"Child thread ID: %u\n", pi.dwThreadId);

      }

 

      // Wait until child process exits.

      wprintf(L"Waiting the child process exits...\n");

      // The time-out interval, in milliseconds. If a nonzero value is specified,

      // the function waits until the object is signaled or the interval elapses.

      // If dwMilliseconds is zero, the function does not enter a wait state if

      // the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE,

      // the function will return only when the object is signaled.

      Ret = WaitForSingleObject( pi.hProcess, INFINITE );

      // WAIT_ABANDONED - 0x00000080L, WAIT_OBJECT_0 - 0x00000000L,

      // WAIT_TIMEOUT - 0x00000102L, WAIT_FAILED - (DWORD)0xFFFFFFFF

      wprintf(L"The WaitForSingleObject() return value is 0X%.8X\n", Ret);

 

    // Close process and thread handles

    wprintf(L"Closing the process and thread handles...\n");

    if(CloseHandle(pi.hProcess) != 0)

            wprintf(L"pi.hProcess handle was closed...\n");

      else

            ErrorHandler(L"CloseHandle(pi.hProcess)");

    if(CloseHandle(pi.hThread) != 0)

            wprintf(L"pi.hThread handle was closed...\n");

      else

            ErrorHandler(L"CloseHandle(pi.hProcess)");

}

 

void ErrorHandler(LPTSTR lpszFunction)

{

    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;

    LPVOID lpDisplayBuf;

    DWORD dw = GetLastError();

 

    FormatMessage(

        FORMAT_MESSAGE_ALLOCATE_BUFFER |

        FORMAT_MESSAGE_FROM_SYSTEM |

        FORMAT_MESSAGE_IGNORE_INSERTS,

        NULL,

        dw,

        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),

        (LPTSTR) &lpMsgBuf,

        0, NULL );

 

    // Display the error message

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(WCHAR));

    StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(WCHAR), L"%s failed with error %d: %s", lpszFunction, dw, lpMsgBuf);

    MessageBox(NULL, (LPCTSTR) lpDisplayBuf, L"Error", MB_OK);

 

    // Free error-handling buffer allocations

    LocalFree(lpMsgBuf);

    LocalFree(lpDisplayBuf);

}

 

Build and run the project. The following screenshot is a sample output without any argument.

 

Creating Processes Program Example: A sample console program output in action without any argument

 

Build and run the project. The following screenshot is a sample output with an argument that invoking the ipconfig /all command.

 

Creating Processes Program Example: A sample console program output in action with an argument - ipconfig /all 1

 

The following is the another portion of the output.

 

Creating Processes Program Example: A sample console program output in action with an argument - ipconfig /all 2

 

If CreateProcess() succeeds, it returns a PROCESS_INFORMATION structure containing handles and identifiers for the new process and its primary thread. The thread and process handles are created with full access rights, although access can be restricted if you specify security descriptors. When you no longer need these handles, close them by using the CloseHandle() function. You can also create a process using the CreateProcessAsUser() or CreateProcessWithLogonW() function. This allows you to specify the security context of the user account in which the process will execute.

 

 

 

< Processes & Threads 16 | Win32 Process & Thread Programming | Win32 Programming | Processes & Threads 18 >