Windows System Programming Third Edition


Additional Utility Programs



Download 3.41 Mb.
Page29/31
Date31.07.2017
Size3.41 Mb.
#24970
1   ...   23   24   25   26   27   28   29   30   31

Additional Utility Programs


Three additional utility programsOptions, SkipArg, and GetArgsare sufficiently useful to list here. None, however, is dependent on Win32.

Options.c


This function scans the command line for words with the "-" (hyphen) prefix, examines the individual characters, and sets Boolean parameters. It is similar to the UNIX getopt function, but it is not as powerful.
Program A-7. Options Function

/* Utility function to extract option flags from the command line. */
#include "EvryThng.h"

#include

DWORD Options (int argc, LPCTSTR argv [], LPCTSTR OptStr, ...)
/* argv is the command line. The options, if any, start

with a '-' in argv [1], argv [2], ....

OptStr is a text string containing all possible

options, in one-to-one correspondence with the addresses of

Boolean variables in the variable argument list (...). These

flags are set if and only if the corresponding option character

occurs in argv [1], argv [2], .... The return value is the argv

index of the first argument beyond the options. */

{

va_list pFlagList;



LPBOOL pFlag;

int iFlag = 0, iArg;


va_start (pFlagList, OptStr);

while ((pFlag = va_arg (pFlagList, LPBOOL)) != NULL

&& iFlag < (int) _tcslen (OptStr)) {

*pFlag = FALSE;

for (iArg = 1;

!(*pFlag) && iArg < argc &&

argv [iArg] [0] == '-';

iArg++)


*pFlag = _memtchr (argv [iArg], OptStr [iFlag],

_tcslen (argv [iArg])) != NULL;

iFlag++;

}

va_end (pFlagList);



for (iArg = 1; iArg < argc && argv [iArg] [0] == '-'; iArg++);

return iArg;

}


SkipArg.c


This function processes a command line string to skip over a white-space-delimited field. It is first used in timep, Program 6-2.
Program A-8. SkipArg Function

/* SkipArg.c

Skip one command line argument -- skip tabs and spaces. */


#include "EvryThng.h"
LPTSTR SkipArg (LPCTSTR targv)

{

LPTSTR p;



p = (LPTSTR) targv;

/* Skip up to the next tab or space. */

while (*p != '\0' && *p != TSPACE && *p != TAB) p++;

/* Skip over tabs and spaces to the next arg. */

while (*p != '\0' && (*p == TSPACE || *p == TAB)) p++;

return p;

}


GetArgs.c


This function scans a string for space- and tab-delimited words and puts the results in a string array passed to the function. It is useful for converting a command line string into an argv [] array, and it is used initially with JobShell in Chapter 6. The Win32 function CommandLineToArgvW performs the same function but is limited to Unicode characters.
Program A-9. GetArgs Function

/* GetArgs. Put command line string in argc/argv form. */

#include "EvryThng.h"


VOID GetArgs (LPCTSTR Command, int *pArgc, LPTSTR argstr [])

{

int i, icm = 0;



DWORD ic = 0;
for (i = 0; ic < _tcslen (Command); i++) {

while (ic < _tcslen (Command) &&

Command [ic] != TSPACE && Command [ic] != TAB) {

argstr [i] [icm] = Command [ic];

ic++; icm++;

}

argstr [i] [icm] = '\0';



while (ic < _tcslen (Command) &&

(Command [ic] == TSPACE || Command [ic] == TAB))

ic++;

icm = 0;


}

if (pArgc != NULL) *pArgc = i;

return;

}

Appendix B. Windows, UNIX, and C Library Comparisons



The tables in this appendix show the Windows (Win32 and Win64) functions described in the main text along with the corresponding UNIX/Linux[1] and ANSI Standard C library functions, if any.

[1] More precisely, "UNIX" means the POSIX functions specified in The Single UNIX Specification (http://www.opengroup.org/onlinepubs/007908799/). UNIX and Linux implement this specification. In turn, the specification has its historical origins in UNIX.

The tables are arranged by chapter (some chapters are combined). Within each chapter, they are sorted first by functionality area (file system, directory management, and so on) and then by the Windows function name.

Each table row gives the following information:



  • The functionality area (subject)

  • The Windows function name

  • The corresponding UNIX function name. In some cases, there are more than one.

  • The corresponding C library function name, if any

  • Comments as appropriate

The notation used in the tables requires some explanation.

  • The Microsoft Visual C++ library contains some UNIX compatibility functions. For example, _open is the compatibility library function for UNIX open. If the UNIX function is in italics, there is a compatibility function. An asterisk next to the name indicates that there is also a wide character Unicode version. For example, there is a _wopen function.

  • A program that uses just the Standard C library, and no Windows or UNIX system functions, should compile, build, and run on both systems if normal precautions are taken. Such a program will, however, be limited to file and I/O operations.

  • Commas separating functions indicate alternatives, often using different characteristics or emulating one aspect of the Windows function.

  • Semicolons separating functions indicate that you use the functions in sequence to emulate the Windows function. Thus, fork; exec corresponds to CreateProcess.

  • An underlined entry indicates a global variable, such as errno.

  • In a few cases, the UNIX equivalent may be stated imprecisely in terms such as "terminal I/O" for Windows functions such as AllocConsole. Often, "Use C library" is the appropriate comment, as in the case of GetTempFileName. In other cases, the situation is reversed. Thus, under the UNIX signal management functions (sigaddset and so on), the Windows entry is "Use SEHVEH" to indicate that the programmer should set up structured or vectored exception handlers and filter functions to get the desired behavior. Unlike UNIX, Windows does not support process groups, so the Windows entries are "N/A," although job management, as done by the programs in Chapter 6, could emulate process relationships.

  • There are numerous "N/A" entries, especially for the C library, if there is no comparable function or set of functions. This is the case, for example, with directory management.

  • The POSIX threads (Pthreads) functions are the UNIX equivalents shown in the tables for Chapters 710, even though they are not properly a part of UNIX. Furthermore, even though many UNIX implementations have their own synchronization objects similar to events, mutexes, and semaphores, there is no attempt to list them here.

Generally, the correspondence is more precise in the earlier chapters, particularly for file management. The systems tend to diverge with the more advanced functionality and, in many cases, there is no C library equivalent. For example, the UNIX and Windows security models differ significantly, so the relationships shown are, at best, approximations.

These functional correspondences are not exact. There are many differences, small and large, among the three systems. Therefore, these tables are only for guidance. The individual chapters discuss many of the differences.


Chapters 2 and 3: File and Directory Management


Subject

Windows

UNIX

C Library

Comments

Console I/O

AllocConsole

terminal I/O

N/A

 

Console I/O

FreeConsole

terminal I/O

N/A

 

Console I/O

ReadConsole

read

getc, scanf, gets

 

Console I/O

SetConsoleMode

ioctl

N/A

 

Console I/O

WriteConsole

write

putc, printf, puts

 

Directory Mgt

CreateDirectory

mkdir*

N/A

Make a new directory

Directory Mgt

FindClose

closedir*

N/A

Close a directory search handle

Directory Mgt

FindFirstFile

opendir*,readdir*

N/A

Find first file matching a pattern

Directory Mgt

FindNextFile

readdir*

N/A

Find subsequent files

Directory Mgt

GetCurrentDirectory

getcwd*

N/A

 

Directory Mgt

GetFullPathName

N/A

N/A

 

Directory Mgt

GetSystemDirectory

Well-known pathnames

N/A

 

Directory Mgt

RemoveDirectory

rmdir, unlink*

remove

 

Directory Mgt

SearchPath

Use opendir, readdir

N/A

Search for a file on a specified path

Directory Mgt

SetCurrentDirectory

chdir*, fchdir

N/A

Change the working directory

Error Handling

FormatMessage

strerror

perror

 

Error Handling

GetLastError

errno

errno

Global variable

Error Handling

SetLastError

errno

errno

Global variable

File Locking

LockFile

fcntl (cmd=F_GETLK, ..)

N/A

 

File Locking

LockFileEx

fcntl (cmd=F_GETLK, ..)

N/A

 

File Locking

UnlockFile

fcntl (cmd=F_GETLK, ..)

N/A

 

File Locking

UnlockFileEx

fcntl (cmd=F_GETLK, ..)

N/A

 

File System

CloseHandle (file handle)

close*

fclose

CloseHandle is not limited to files

File System

CopyFile

open; read; write; close

fopen; fread; fwrite; fclose

Duplicate a file

File System

CreateFile

open*,creat*

fopen

Open/create a file

File System

DeleteFile

unlink*

remove

Delete a file

File System

FlushFileBuffers

fsynch

fflush

Write file buffers

File System

GetFileAttributes

stat*,fstat*, lstat

N/A

 

File System

GetFileInformationByHandle

stat*,fstat*, lstat

N/A

Fill structure with file info

File System

GetFileSize

stat*,fstat*, lstat

ftell, fseek

Get length of file in bytes

File System

GetFileTime

stat*,fstat*, lstat

N/A

 

File System

GetFileType

stat*,fstat*, lstat

N/A

Check for character stream device or file

File System

GetStdHandle

Use file desc 0, 1, or 2

Use stdin, stdout, stderr

 

File System

GetTempFileName

Use C library

tmpnam

Create a unique file name

File System

GetTempFileName, CreateFile

Use C library

tmpfile

Create a temporary file

File System

GetTempPath

/temp path

N/A

Directory for temp files

File System

MoveFile, MoveFileEx

Use C library

rename

Rename a file or directory

File System

CreateHardLink

link,unlink*

N/A

Windows does not support links

File System

N/A

symlink

N/A

Create a symbolic link

File System

N/A

readlink

N/A

Read name in a symbolic link

File System

N/A, ReadFile returns 0 bytes

N/A, read returns 0 bytes

feof

Rest for end of file

File System

N/A, use multiple ReadFiles

readv

N/A, use multiple freads

Scatter read

File System

N/A, use multiple WriteFiles

writev

N/A, use multiple fwrites

Gather write

File System

ReadFile

read

fread

Read data from a file

File System

SetEndOfFile

chsize*

N/A

 

File System

SetFileAttributes

fcntl

N/A

 

File System

SetFilePointer

lseek

fseek

Set file pointer

FileSystem

SetFilePointer (to 0)

lseek (0)

rewind

 

File System

SetFileTime

utime*

N/A

 

File System

SetStdHandle

close,dup*,dup2*, or fcntl

freopen

dup2 or fcntl

File System

WriteFile

write

fwrite

Write data to a file

System Info

GetdiskFreeSpace

N/A

N/A

 

System Info

GetSystemInfo

getrusage

N/A

 

System Info

GetVersion

uname

N/A

 

System Info

GetVolumeInformation

N/A

N/A

 

System Info

GlobalMemoryStatus

getrlimit

N/A

 

System Info

Various defined constants

sysconf, pathconf, fpathconf

N/A

 

Time

GetSystemTime

Use C library

time, gmtime

 

Time

See ls program, Program 3-2

Use C library

asctime

 

Time

CompareFileTime

Use C library

difftime

Compare "calendar" times

Time

FileTimeToLocalFileTime, FileTimeToSystemTime

Use C library

localtime

 

Time

FileTimeToSystemTime

Use C library

gmtime

 

Time

GetLocalTime

Use C library

time, localtime

 

Time

See touch program, Program 3-3

Use C library

strftime

 

Time

SetLocalTime

N/A

N/A

 

Time

SetSystemTime

N/A

N/A

 

Time

Subtract file times

Use C library

difftime

 

Time

SystemTimeToFileTime

Use C library

mktime

 




Chapter 4: Exception Handling


Subject

Windows

UNIX

C Library

SEH

_TRy _except

Use C library signals

Use C library signals

SEH

_try _finally

Use C library signals

Use C library signals

SEH

AbnormalTermination

Use C library signals

Use C library signals

SEH

GetExceptionCode

Use C library signals

Use C library signals

SEH

RaiseException

Use C library signals

signal, raise

Signals

Use _finally block

Use C library

atexit

Signals

Use C library or terminate process

kill

raise

Signals

Use C library

Use C library

signal

Signals

Use SEH, VEH

sigemptyset

N/A

Signals

Use SEH, VEH

sigfillset

N/A

Signals

Use SEH, VEH

sigaddset

N/A

Signals

Use SEH, VEH

sigdelset

N/A

Signals

Use SEH, VEH

sigismember

N/A

Signals

Use SEH, VEH

sigprocmask

N/A

Signals

Use SEH, VEH

sigpending

N/A

Signals

Use SEH, VEH

sigaction

N/A

Signals

Use SEH, VEH

sigsetjmp

N/A

Signals

Use SEH, VEH

siglongjmp

N/A

Signals

Use SEH, VEH

sigsuspendf

N/A

Signals

Use SEH, VEH

psignal

N/A

Signals

Use SEH, VEH, or C library

Use C library

abort

Note: Many UNIX vendors provide proprietary exception handling capabilities.




Chapter 5: Memory Management, Memory-Mapped Files, and DLLs


Subject

Windows

UNIX

C Library

Mapped Files

CreateFileMapping

shmget

N/A

Mapped Files

MapViewOfFile

mmap, shmat

N/A

Mapped Files

MapViewOfFileEx

mmap, shmat

N/A

Mapped Files

OpenFileMapping

shmget

N/A

Mapped Files

UnmapViewOfFile

munmap, shmdt, shmctl

N/A

Memory Mgt

GetProcessHeap

N/A

N/A

Memory Mgt

GetSystemInfo

N/A

N/A

Memory Mgt

HeapAlloc

sbrk, brk, or C library

malloc, calloc

Memory Mgt

HeapCreate

N/A

N/A

Memory Mgt

HeapDestroy

N/A

N/A

Memory Mgt

HeapFree

Use C library

free

Memory Mgt

HeapReAlloc

Use C library

realloc

Memory Mgt

HeapSize

N/A

N/A

Shared Memory

CloseHandle (map handle)

shmctl

N/A

Shared Memory

CreateFileMapping, OpenFileMapping

shmget

N/A

Shared Memory

MapViewOfFile

shmat

N/A

Shared Memory

UnmapViewOfFile

shmdt

N/A

DLLs

LoadLibrary

dlopen

N/A

DLLs

FreeLibrary

dlclose

N/A

DLLs

GetProcAddress

dlsyn

N/A

DLLs

DllMain

pthread_once

N/A




Chapter 6: Process Management


Subject

Windows

UNIX

C Library

Comments

Process Mgt

CreateProcess

fork ();execl ()*, system()

N/A

There are 6 execxx functions

Process Mgt

ExitProcess

_exit

exit

 

Process Mgt

GetCommandLine

argv []

argv []

 

Process Mgt

GetCurrentProcess

getpid*

N/A

 

Process Mgt

GetCurrentProcessId

getpid*

N/A

 

Process Mgt

GetEnvironmentStrings

N/A

getenv

 

Process Mgt

GetEnvironmentVariable

N/A

getenv

 

Process Mgt

GetExitCodeProcess

wait, waitpid

N/A

 

Process Mgt

GetProcessTimes

times, wait3, wait4

N/A

 

Process Mgt

GetProcessWorkingSetSize

wait3, wait4

N/A

 

Process Mgt

N/A

execl*, execv*, execle*, execve*, execlp*, execvp*

N/A

Windows does not have a direct equivalent

Process Mgt

N/A

fork, vfork

N/A

Windows does not have a direct equivalent

Process Mgt

N/A

getppid

N/A

No parent/child relationships in Windows

Process Mgt

N/A

getgid, getegid

N/A

No process groups in Windows

Process Mgt

N/A

getpgrp

N/A

 

Process Mgt

N/A

setpgid

N/A

 

Process Mgt

N/A

setsid

N/A

 

Process Mgt

N/A

tcgetpgrp

N/A

 

Process Mgt

N/A

tcsetpgrp

N/A

 

Process Mgt

OpenProcess

N/A

N/A

 

Process Mgt

SetEnvironmentVariable

putenv

N/A

putenv is not part of the Standard C library

Process Mgt

TerminateProcess

kill

N/A

 

Synch: Process

WaitForMultipleObjects (process handles)

waitpid

N/A

 

Synch: Process

WaitForSingleObject (process handle)

wait, waitpid

N/A

 

Timers

KillTimer

alarm (0)

N/A

 

Timers

SetTimer

alarm

N/A

 

Timers

Sleep

sleep

N/A

 

Timers

Sleep

poll or select, no file descriptor

N/A

 




Chapter 7: Threads and Scheduling


Subject

Windows

UNIX/Pthreads

Comments

Thread Mgt

CreateRemoteThread

N/A

 

TLS

TlsAlloc

pthread_key_alloc

 

TLS

TlsFree

pthread_key_delete

 

TLS

TlsGetValue

pthread_getspecific

 

TLS

TlsSetValue

pthread_setspecific

 

Thread Mgt

CreateThread, _beginthreadex

pthread_create

 

Thread Mgt

ExitThread, _endthreadex

pthread_exit

 

Thread Mgt

GetCurrentThread

pthread_self

 

Thread Mgt

GetCurrentThreadId

N/A

 

Thread Mgt

GetExitCodeThread

pthread_yield

 

Thread Mgt

ResumeThread

N/A

 

Thread Mgt

SuspendThread

N/A

 

Thread Mgt

TerminateThread

pthread_cancel

pthread_cancel is safer

Thread Mgt

WaitForSingleObject(thread handle)

pthread_join

 

Thread Priority

GetPriorityClass

pthread_attr_getschedpolicy, getpriority

 

Thread Priority

GetThreadPriority

pthread_attr_getschedparam

 

Thread Priority

SetPriorityClass

pthread_attr_setschedpolicy, setpriority, nice

 

Thread Priority

SetThreadPriority

pthread_attr_setschedparam

 

Note: Pthreads, while a part of all modern UNIX offerings, are available on non-UNIX systems as well.




Chapters 810: Thread Synchronization


Subject

Windows

UNIX/Pthreads

Comments

Synch: CritSec

DeleteCriticalSection

Use mutexes to emulate critical sections. Some systems provide proprietary equivalents.

C library is not applicable

Synch: CritSec

EnterCriticalSection

C library is not applicable

Synch: CritSec

InitializeCriticalSection

 

Synch: CritSec

LeaveCriticalSection

 

Synch: Event

CloseHandle (event handle)

pthread_cond_destroy

 

Synch: Event

CreateEvent

pthread_cond_init

 

Synch: Event

PulseEvent

pthread_cond_signal

Manual-reset event

Synch: Event

ResetEvent

N/A

 

Synch: Event

SetEvent

pthread_cond_broadcast

Auto-reset event

Synch: Event

WaitForSingleObject (event handle)

pthread_cond_wait

 

Synch: Event

WaitForSingleObject (event handle)

pthread_timed_wait

 

Synch: Mutex

CloseHandle (mutex handle)

pthread_mutex_destroy

 

Synch: Mutex

CreateMutex

pthread_mutex_init

 

Synch: Mutex

ReleaseMutex

pthread_mutex_unlock

 

Synch: Mutex

WaitForSingleObject (mutex handle)

pthread_mutex_lock

 

Synch: Sem

CreateSemaphore

semget

 

Synch: Sem

N/A

semctl

Windows does not directly support all these options

Synch: Sem

OpenSemaphore

semget

 

Synch: Sem

ReleaseSemaphore

semop (+)

 

Synch: Sem

WaitForSingleObject (semaphore handle)

semop (-)

Windows can wait for only one count




Chapter 11: Interprocess Communication


Subject

Windows

UNIX

C Library

Comments

IPC

CallNamedPipe

N/A

N/A

CreateFile, WriteFile, ReadFile, CloseHandle

IPC

CloseHandle (pipe handle)

close, msgctl

pclose

Not part of the Standard C librarysee Stevens

IPC

ConnectNamedPipe

N/A

N/A

 

IPC

CreateMailslot

N/A

N/A

 

IPC

CreateNamedPipe

mkfifo, msgget

N/A

 

IPC

CreatePipe

pipe

popen

Not part of the Standard C librarysee Stevens

IPC

DuplicateHandle

dup, dup2, or fcntl

N/A

Or use file names CONIN$, CONOUT$

IPC

GetNamedPipeHandleState

stat, fstat, lstat64

N/A

 

IPC

GetNamedPipeInfo

stat, fstat, lstat

N/A

 

IPC

ImpersonateNamedPipeClient

N/A

N/A

 

IPC

PeekNamedPipe

N/A

N/A

 

IPC

ReadFile (named pipe handle)

read (fifo), msgsnd

N/A

 

IPC

RevertToSelf

N/A

N/A

 

IPC

SetNamedPipeHandleState

N/A

N/A

 

IPC

transactNamedPipe

N/A

N/A

WriteFile; ReadFile

IPC

WriteFile (named pipe handle)

write (fifo), msgrcv

N/A

 

Misc.

GetComputerName

uname

N/A

 

Misc.

SetComputerName

N/A

N/A

 

Security

SetNamedPipeIdentity

Use directory sticky bit

N/A

 




Chapter 14: Asynchronous I/O


Subject

Windows

UNIX

C Library

Comments

Asynch I/O

GetOverlappedResult

N/A

N/A

 

Asynch I/O

ReadFileEx

N/A

N/A

Extended I/O with completion routine

Asynch I/O

SleepEx

N/A

N/A

Alertable wait

Asynch I/O

WaitForMultipleObjects (file handles)

poll, select

N/A

 

Asynch I/O

WaitForMultipleObjectsEx

N/A

N/A

Alertable wait

Asynch I/O

WriteFileEx

N/A

N/A

Extended I/O with completion routine

Asynch I/O

WaitForSingleObjectEx

waitpid

N/A

Alertable wait




Chapter 15: Securing Windows Objects


Subject

Windows

UNIX

Comments

Security

AddAccessAllowedAce

chmod, fchmod

C library does not support security

прямоугольник 1

Security

AddAccessDeniedAce

chmod, fchmod

Security

AddAuditAce

N/A

Security

CreatePrivateObjectSecurity

N/A

Security

DeleteAce

chmod, fchmod

Security

DestroyPrivateObjectSecurity

N/A

Security

GetAce

stat*,fstat*, lstat

Security

GetAclInformation

stat*,fstat*, lstat

Security

GetFileSecurity

stat*,fstat*, lstat

Security

GetPrivateObjectSecurity

N/A

Security

GetSecurityDescriptorDacl

stat*,fstat*, lstat

Security

GetUserName

getlogin

Security

InitializeAcl

N/A

Security

InitializeSecurityDescriptor

Umask

Security

LookupAccountName

getpwnam, getgrnam

Security

LookupAccountSid

getpwuid, getuid, geteuid

Security

N/A

getpwend, setpwent, endpwent

Security

N/A

getgrent, setgrent, endgrent

Security

N/A

Setuid, seteuid, setreuid

Security

N/A

Setgid, setegid, setregid

Security

OpenProcessToken

getgroups, setgroups, initgroups

Security

SetFileSecurity

chmod*, fchmod

Security

SetPrivateObjectSecurity

N/A

Security

SetSecurityDescriptorDacl

Umask

Security

SetSecurityDescriptorGroup

chown, fchown, lchown

Security

SetSecurityDescriptorOwner

chown, fchown, lchown

Security

SetSecurityDescriptorSacl

N/A





Directory: bitstream -> NAU
bitstream -> A mathematical theory of communication
bitstream -> Images of Fairfax in Modern Literature and Film Andrew Hopper
bitstream -> Amphitheater High School’s Outdoor Classroom: a study in the Application of Design
bitstream -> Ethics of Climate Change: Adopting an Empirical Approach to Moral Concern
bitstream -> The Age of Revolution in the Indian Ocean, Bay of Bengal and South China Sea: a maritime Perspective
bitstream -> Methodism and Culture
bitstream -> Review of coastal ecosystem management to improve the health and resilience of the Great Barrier Reef World Heritage Area
bitstream -> Present state of the area
NAU -> International significance of icao alphabet for flight safety
NAU -> Performance comparison of android runtime and dalvik environments on an android device

Download 3.41 Mb.

Share with your friends:
1   ...   23   24   25   26   27   28   29   30   31




The database is protected by copyright ©ininet.org 2024
send message

    Main page