digitalmars.com                      
Last update Sun Mar 4 12:00:59 2018

process.h


_beginthread

Header
process.h
Prototype
unsigned long _beginthread(void(* func)(void*), unsigned stack_size, void *arg);
Description
This function creates a new thread of execution within the current process. Thread execution starts at the beginning of func. To terminate the thread correctly, func must call _endthread, freeing memory allocated by the run time library to support the thread.

The operating system allocates a stack for the thread containing the number of bytes specified by stack_size. If stack_size is zero, the operating system creates a stack the same size as that of the main thread.

The operating system passes arg to func when execution begins. arg can be any 32-bit value cast to void *.

Return Value
Returns the operating system handle of the newly created thread. If unsuccessful, the function returns -1 and sets errno.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_endthread _threadid
Example
/* Example for _beginthread,  _endthread
  DBLCOPY.C

Copies a file using double-buffering.
There are two threads. One reads from
the file, the other writes. Since there
are two buffers, the read-thread can
read ahead into the second buffer while
the write-thread is still writing from
the first buffer. Each thread goes into
a wait while its I/O completes, allowing
the other thread to resume. Two
semaphores coordinate access to the
buffers. The full semaphore is signalled
when the read-thread has filled a buffer.
This wakes up the write-thread so that it
can write. The empty semaphore is
signalled when the write-thread has
written a buffer. This wakes up the
read-thread so it can read another buffer.
*/

#include <process.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <windows.h>

static void error(char *action)
{
  fprintf(stderr, "Error %s: %d\n", action, GetLastError());
  exit(EXIT_FAILURE);
}

static void status (char *action, int buffer)
{
  printf("%s buffer %d\n", action, buffer + 1);
}

static HANDLE source, dest, full, empty;
static char buffer[2][0xffff];
static int size[2];

static void read_file(void *unused)
{
 int code, i;
 OVERLAPPED overlap;

 overlap.Offset = 0;
 overlap.OffsetHigh = 0;
 overlap.hEvent = CreateEvent(NULL, FALSE, FALSE, "_beginth_event1");
 if (overlap.hEvent == NULL)
    error("creating read event");
 for (i = 0; ; i = (i + 1) % 2)
 {
  if (WaitForSingleObject(empty, INFINITE) == -1)
      error("waiting for empty buffer");
  status("Reading", i);
  if (!ReadFile(source, buffer[i], sizeof buffer[i], size + i, &overlap))
     switch (GetLastError ())
     {
     case ERROR_IO_PENDING:
        if (WaitForSingleObject(overlap.hEvent, INFINITE) == -1)
           error("waiting for overlapped read");
        break;
     case ERROR_HANDLE_EOF:
        break;
     default:
        error (" reading");
     }
  status("Done reading", i);
  ReleaseSemaphore(full, 1, NULL);
  if (size[i] == 0)
     break;
  overlap.Offset += size[i];
 }
 _endthread ();
}

static void write_file (void *unused)
{
 int code, i, written;
 OVERLAPPED overlap;

 overlap.Offset = 0;
 overlap.OffsetHigh = 0;
 overlap.hEvent = CreateEvent(NULL, FALSE, FALSE, "_beginth_event2");
 for (i = 0; ; i = (i + 1) % 2)
 {
  if (WaitForSingleObject(full, INFINITE) == -1)
     error("waiting for full buffer");
  if (size[i] == 0)
     break;
  status("Writing", i);
  if (!WriteFile(dest, buffer[i], size[i], &written, &overlap))
     if (GetLastError() == ERROR_IO_PENDING)
     {   if (WaitForSingleObject(overlap.hEvent, INFINITE) == -1)
           error("waiting for overlapped write");
     }
     else
        error("writing");
  status("Done writing", i);
  overlap.Offset += written;
  ReleaseSemaphore(empty, 1, NULL);
 }
 _endthread();
}

void main(int argc, char const *const argv[])
{
 HANDLE thread[2];
 int code;

 if (argc != 3)
 {
  fprintf(stderr, "Usage: DBLCOPY source-file destination-file\n");
  exit(EXIT_FAILURE);
 }
 printf("Copying %s to %s\n",
        argv[1], argv[2]);

 source = CreateFile(argv[1],
        GENERIC_READ,
        FILE_SHARE_READ, NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,
        NULL);
 if (source == INVALID_HANDLE_VALUE)
  error("opening source file");
 dest = CreateFile(argv[2], GENERIC_WRITE,
     FILE_SHARE_READ, NULL,
     CREATE_NEW, FILE_FLAG_OVERLAPPED,
     NULL);
 if (dest == INVALID_HANDLE_VALUE)
  error("opening destination file");

 full = CreateSemaphore(NULL, 0, 2, "_beginth_sema1");
 if (full == NULL)
  error("creating full semaphore");
 empty = CreateSemaphore(NULL, 2, 2, "_beginth_sema2");
 if (empty == NULL)
  error("creating empty semaphore");

 thread[0] = (HANDLE)_beginthread(read_file, 0, NULL);
 if (thread[0] == INVALID_HANDLE_VALUE)
  error("creating read thread");
 thread[1] = (HANDLE)_beginthread(write_file, 0, NULL);
 if (thread[1] == INVALID_HANDLE_VALUE)
  error("creating write thread");

 if (WaitForMultipleObjects(2, thread, TRUE, INFINITE) == -1)
  error("waiting for threads");

 if (!CloseHandle(source))
  error("closing source file");
 if (!CloseHandle(dest))
  error("closing destination file");

 printf("Done\n");
}
Output
c:\dm\examples> dblcopy bigfile bigcopy
Copying bigfile to bigcopy
Reading buffer 1
Done reading buffer 1
Reading buffer 2
Done reading buffer 2
Writing buffer 1
Done writing buffer 1
Writing buffer 2
Reading buffer 1
Done writing buffer 2
Done reading buffer 1
Reading buffer 2
Writing buffer 1
Done reading buffer 2
Done writing buffer 1
Writing buffer 2
Done writing buffer 2
Reading buffer 1
Done reading buffer 1
Done

_c_exit, _cexit

Header
process.h
Prototype
void _c_exit(void);
void _cexit(void);
Description
The _c_exit and _cexit functions perform cleanup operations and return without terminating the calling process. The _c_exit function performs a quick C library termination procedure and returns to the caller without processing registered exit functions (atexit or _onexit) or flushing buffers.

In contrast, the _cexit function performs a complete C library termination procedure by calling registered exit functions in LIFO order, flushing all I/O buffers, and closing all open streams before returning to the caller.

Both functions restore interrupt vectors altered by the startup code.

Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
abort atexit _fatexit _exec Functions exit _exit _spawn Functions
Example
/* Example for _c_exit and _cexit
   Also demonstrates atexit
*/
#include <process.h>
#include <stdio.h>
#include <stdlib.h>

void __cdecl near_exit_function(void)
{
 printf("In the atexit function\n");
}

void main()
{
 atexit(near_exit_function);

 _c_exit();
 printf("Shouldn't have called the atexit function yet.\n");
 _cexit();
 printf("Should have called the atexit function now.\n");
}
Output
Shouldn't have called the atexit function yet.
In the atexit function
Should have called the atexit function now.
In the atexit function

_exec Functions

Header
process.h
Prototype
int _execl(const char *path, const char *arg0,... const char *argn, NULL);
int _execle(const char *path, const char *arg0,... const char *argn, NULL, const char *const *envp);
int _execlp(const char *path, const char *arg0,... const char *argn, NULL);
int _execlpe(const char *path, const char *arg0,... const char *argn, NULL);
int _execv(const char *path, const char *const *argv);
int _execve(const char *path, const char *const *argv, const char *const *envp);
int _execvp(const char *path, const char *const *argv);
int _execvpe(const char *path, const char *const *argv, const char *const *envp);
Description
These functions load and execute a new child process by placing it in memory previously occupied by the calling process. Sufficient memory must be available.

Argument path specifies the path name of the file executed as a child process. arg0 through argn is a list of pointers to arguments to be passed to the child process. argv is an array of pointers to arguments. envp is an array of pointers to environment settings.

The base of each function is _exec, followed by one or more letters.

Letter Meaning
e An array of pointers to environment arguments is explicitly passed to the child process.
l Command line arguments are passed individually to the function.
p Uses the PATH argument variable to find the file to be executed.
v Command line arguments are passed to the function as an array of pointers.
Files open when an _exec call is made remain open in the new process. In the _execl, _execlp, _execv, and _execvp calls, the child process inherits the parent's environment. The _execle, _execlpe, _execve, and _execvpe calls alter the enviroment for the child process by passing a list of environment settings through the envp argument. This argument is an array of character pointers; each element (except for the final element) points to a null-terminated string defining an environment variable.

Each null-terminated string has the form

NAME=value

NAME is the environment variable name; value is the string value to which that variable is set. (value is not enclosed in double quotation marks.) The final element of the envp array must be NULL. When envp itself is NULL, the child process inherits the environment setttings of the parent process.

A program executed with one of the _exec functions is always loaded into memory as if the "maximum allocation" in the program's .exe file header is set to default value 0xFFFFH. You can use the EXEHDR utility to change the maximum allocation field of a program. However, if you do this and then invoke the program with one of the _exec functions, the program might behave differently from a program invoked directly from the operating-system command line or with one of the _spawn functions.

By checking the first two bytes of a file, command. com determines if the file is an .exe file or a .com file. The _exec functions can execute a file named by any extension, as long as its content is executable. You can also execute .bat files

The _exec calls do not preserve the translation modes of open files. If the child process uses files inherited from the parent, use the _setmode function to set the translation mode to the desired mode.

You must flush or close all open files before an _exec call.

Synonym
Functions: execl, execle, execlp, execlpe, execv, execve, execvp, execvpe
Return Value
The _exec functions do not normally return to the calling process. If an exec function returns, an error occurred, the return value is -1, and errno is set to one of the following values:

Value Description
E2BIG The argument list exceeds the system limit.
EACCES The specified file has a locking or sharing violation.
ENOENT The file or path name not found.
ENOMEM Not enough memory is available to execute the child process.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
abort atexit _fatexit exit _exit _onexit _fonexit _spawn Functions system
Example
/* Example of _exec
   dumparg.exe (see the _spawn function)
   must also be compiled to use this
   example
*/
#include <stdio.h>
#include <stdlib.h>
#include <process.h>

void main ()
{
 char argstr[128];
 printf("Enter parameters: ");
 gets(argstr);

 if (_execlp("dumparg.exe", "dumparg.exe",
     argstr, NULL) == -1)
 {
   perror("Could not spawn process");
   exit(EXIT_FAILURE);
 }
}
Output
Enter parameters: Cat  Dog  Mouse  Shirt  Tie  Tail

Cat
Dog
Mouse
Shirt
Tie
Tail

_endthread

Header
process.h
Prototype
void _endthread (void);
Description
The _endthread function terminates a thread created by _beginthread. Always call _endthread from within the thread function rather than just returning from the thread function; _enthread frees data structures created by _beginthread.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_beginthread _threadid

_getpid

Header
process.h
Prototype
int _getpid(void);
Description
The _getpid function returns the process identification number (process ID) for the calling process. The ID uniquely identifies a process.
Synonym
Function: getpid
Return Value
Both functions return the process ID. There is no error return.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
getpsp
Example
/* Example for _getpid */

#include <stdio.h>
#include <process.h>

void main()
{
 printf("The process id of this program is %d\n",
        getpid());
}
Output
The process id of this program is 7640

_spawn Functions

Header
process.h (for spawn and _spawn functions)
stdio.h (for _spawn functions only)
Prototype
int _spawnl(int mode, char *filename, char *arg0,..., char *argn, NULL);
int _spawnle(int mode, char *filename, char *arg0,.., char *argn, NULL, char ** envp);
int _spawnlp(int mode, char *filename, char *arg0,..., char *argn, NULL);
int _spawnlpe(int mode, char *filename, char *arg0,..., char *argn, NULL, char ** envp);
int _spawnv(int mode, char *filename, char ** argv);
int _spawnve(int mode, char *filename, char ** argv, char ** envp);
int _spawnvp(int mode, char *filename, char ** argv);
int _spawnvpe(int mode, char *filename, char ** argv, char ** envp);
Description
The _spawn functions load and execute a new child process. The current process may or may not continue to execute asynchronously. Creating a new subprocess requires enough memory in which both the child process and the current program can execute.

The mode argument determines whether the child process runs asynchronously. Values for mode are:

Value Description
_P_OVERLAY Overlays parent process with child, which destroys the parent. This has the same effect as the _exec and exec functions.
_P_WAIT Suspends parent process until the child process has finished executing.
The filename argument specifies the program to execute. For spawnlp and spawnvp only, if the filename does not have a path and is not in the current directory, the environment variable PATH determines which directories to search for the file. The string pointed to by argv[0] is the name of the program to run.

The command line passed to the spawned program is made up of the character strings, arg0 through argn, in the spawn call. The combined length of these strings must not exceed 128 characters. The argv argument is an array of character pointers. The last pointer in argv must be NULL to indicate the end of the list.

Files that are open when a spawn call is made remain open in the child process. In the _spawnl, _spawnlp, _spawnv, and _spawnvp calls, the child process inherits the environment of the parent. The _spawnle, _spawnlpe, _spawnve, and _spawnvpe calls allow the user to alter the child process's environment by passing a list of environment settings using the envp argument. This argument is an array of character pointers; each pointer (except for the last one) points to a null-terminated string defining an environment variable. An environment variable has the form

varname = value

where varname is the variable name and value is the string value (not enclosed in quotation marks.) The last pointer in the array is NULL. When the envp argument is null, the child inherits the parent's environment settings.

The _spawn functions can be used under Microsoft Windows. They use LoadModule to run the spawned process. If this fails an attempt is made to spawn a normal MS-DOS process. If a Windows application is spawned, the instance handle can be obtained using exec_instancehandleget.

It is possible to specify how the spawned programwill be shown using the functions _exec_showset, _exec_showget and _exec_showreset.

Synonym
Functions: spawnl, spawnle, spawnlp, spawnlpe, spawnv, spawnve, spawnvp, spawnvpe
Return Value
The return value indicates the exit status of the spawned program. A value of 0 indicates that the spawned program executed successfully. A positive value indicates that the spawned program executed, but was aborted or ended in error, the value returned is the exit status of the child process. A negative value indicates that the spawned program did not execute, and errno is set.

Under Microsoft Windows, spawn returns the negated error code returned from LoadModule for compatibility with the C run-time library. The following error codes may be encountered:

Error Code Description
-2 File not found
-3 Path not found
-11 Invalid .exe file (for Windows)
-13 DOS 4.0 application
-14 Unknown .exe type (may be DOS extended)
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_exec Functions
Example
/* Example for _spawn
   Compile program to file: dumparg.exe
*/

#include <stdio.h>

void main(int argc, char *argv[])
{
 int i;
 printf("There are %d command line parameters\n",
        argc - 1);

 for (i = 1; i < argc; i++)
 {
   puts(argv[i]);
 }
}
/* Example of _spawn
   dumparg.exe must also be compiled
   to use this example
*/

#include <stdio.h>
#include <stdlib.h>
#include <process.h>

void main()
{
 char argstr[128];

 printf("Enter some parameters: ");
 gets(argstr);

 if (_spawnlp(_P_WAIT, "dumparg.exe",
     "dumparg.exe", argstr, NULL) == -1)
{
   perror("Could not spawn process");
   exit(EXIT_FAILURE);
}
}
Output
Enter some parameters: Dog Cat Tree House Fence Car Boat
There are 7 command line parameters
Dog
Cat
Tree
House
Fence
Car
Boat
Home | Compiler & Tools | IDDE Reference | STL | Search | Download | Forums