2008年10月22日 星期三

程序與程序間共用記憶體(Shared Memory)

CreateFileMapping

The CreateFileMapping function creates or opens a named or unnamed file mapping object for a specified file.

HANDLE CreateFileMapping(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCTSTR lpName
);

Parameters

hFile
[in] A handle to the file from which to create a mapping object.

The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. It is not required, but it is recommended that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights.

If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a mapping object size in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMapping creates a file mapping object of a specified size that the operating system paging file backs, instead of by a named file in the file system.

The file mapping object can be shared by duplication, inheritance, or by name. The initial contents of the pages in a file mapping object are 0 (zero).

lpAttributes
[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not a returned handle can be inherited by child processes.

If lpAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for a new file mapping object.

If lpAttributes is NULL, the file mapping object gets a default security descriptor. The access control lists (ACL) in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. However, doing this involves potential security risks. To avoid the risks, use a valid SECURITY_ATTRIBUTES structure.

flProtect
[in] The protection for the file view, when the file is mapped.

This parameter can be one of the following values.

Value Meaning
PAGE_READONLY Gives read-only access to a specific region of pages.

An attempt to write to a specific region results in an access violation. The file that the hFile parameter specifies must be created with the GENERIC_READ access right.

PAGE_READWRITE Gives read/write access to a specific region of pages.

The file that hFile specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.

PAGE_WRITECOPY Gives copy-on-write access to a specific region of pages.

The files that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.

PAGE_EXECUTE_READ Gives read and execute access to a specific region of pages.

The file specified by hFile must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.

Windows Server 2003 and Windows XP: This feature is not available until Windows XP SP2 and Windows Server 2003 SP1.
PAGE_EXECUTE_READWRITE Gives read, write, and execute access to a specific region of pages.

The file that hFile specifies must be created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights.

Windows Server 2003 and Windows XP: This feature is not available until Windows XP SP2 and Windows Server 2003 SP1.

An application can specify section attributes by combining (using the bitwise OR operator) one or more of the following section attribute values with one of the preceding page protection values.

Value Meaning
SEC_COMMIT Allocates physical storage in memory or the paging file on disk for all pages of a section.

This is the default setting.

SEC_IMAGE Sets the file that is specified for section file mapping to be an executable image file.

Because the mapping information and file protection are taken from the image file, no other attributes are valid with SEC_IMAGE.

Windows Me/98/95: This flag is not supported.
SEC_NOCACHE Sets all pages of a section to non-cashable.

Applications should not use this flag except when explicitly required for a device. Using the interlocked functions with memory mapped by a SEC_NOCACHE section can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.

SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT to be set.

Windows Me/98/95: This flag is not supported.
SEC_RESERVE Reserves all pages of a section without allocating physical storage.

The reserved range of pages cannot be used by any other allocation operations until the range of pages is released.

Reserved pages can be identified in subsequent calls to the VirtualAlloc function. This attribute is valid only if the hFile parameter is INVALID_HANDLE_VALUE; that is, a file mapping object that the operating system paging file backs.

dwMaximumSizeHigh
[in] A high-order DWORD for the maximum size of a file mapping object.
dwMaximumSizeLow
[in] A low-order DWORD for the maximum size of a file mapping object.

If this parameter and dwMaximumSizeHigh are 0 (zero), the maximum size of the file mapping object is equal to the current size of the file that hFile identifies.

An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should test for files with a length of 0 (zero) and reject those files.

lpName
[in] A pointer to a null-terminated string that specifies the name of a mapping object.

If this parameter matches the name of an existing mapping object that is named, the function requests access to the mapping object with the protection that flProtect specifies.

If this parameter is NULL, the mapping object is created without a name.

If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.

Terminal Services: The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces.
Windows XP: Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next user to log on uses session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal Services so that applications can support multiple users.
Windows 2000: If Terminal Services is not running, the "Global\" and "Local\" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
Windows NT: The name can contain any character except the backslash character.
Windows Me/98/95: The name can contain any character except the backslash character. An empty string ("") is a valid object name.

Return Values

If the function succeeds, the return value is a handle to the file mapping object.

If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), and GetLastError returns ERROR_ALREADY_EXISTS.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

After a file mapping object is created, the size of the file must not exceed the size of the file mapping object; if it does, not all of the file contents are available for sharing.

If an application specifies a size for the file mapping object that is larger than the size of the actual named file on disk, the file on disk is increased to match the specified size of the file mapping object.

If the file cannot be increased, the result is a failure to create the file mapping object, and GetLastError returns ERROR_DISK_FULL.

The handle that CreateFileMapping returns has full access to a new file mapping object, and can be used with any function that requires a handle to a file mapping object. A file mapping object can be shared through process creation, handle duplication, or by name. For more information, see DuplicateHandle and OpenFileMapping.

Windows Me/98/95: File handles that are used to create file mapping objects must not be used in subsequent calls to file I/O functions, such as ReadFile and WriteFile. In general, if a file handle is used in a successful call to the CreateFileMapping function, do not use that handle until you close the corresponding file mapping object.

Creating a file mapping object creates the potential for mapping a view of the file, but does not map the view. The MapViewOfFile and MapViewOfFileEx functions map a view of a file into a process address space.

With one important exception, file views derived from a single file mapping object are coherent or identical at a specific time. If multiple processes have handles of the same file mapping object, they see a coherent view of the data when they map a view of the file.

The exception is related to remote files. Although CreateFileMapping works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer only sees its own writes to the page. When the data gets updated on the disk, it is not merged.

A mapped file and a file that is accessed by using the input and output (I/O) functions (ReadFile and WriteFile) are not necessarily coherent.

To fully close a file mapping object, an application must unmap all mapped views of the file mapping object by calling UnmapViewOfFile, and then close the file mapping object handle by calling CloseHandle.

These functions can be called in any order. The call to UnmapViewOfFile is necessary, because mapped views of a file mapping object maintain internal open handles to the object, and a file mapping object does not close until all open handles to it are closed.

Terminal Services sessions can use shared memory blocks to transfer data between processes those sessions spawn. If you do this, keep in mind that shared memory cannot be used in situations where both of the following conditions exist:

  • All of the processes that use a shared memory block are not spawned by one session.
  • All of the sessions share the same user logon credential.

To guard against an access violation, use structured exception handling to protect any code that writes to or reads from a memory mapped view. For more information, see Reading and Writing From a File View.

To have a mapping with executable permissions, an application must call CreateFileMapping with either PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_READ, and then call MapViewOfFile with FILE_MAP_EXECUTE | FILE_MAP_WRITE or FILE_MAP_EXECUTE | FILE_MAP_READ.

Example Code [C++]

To implement a mapping object creation function that fails if the object already exists, an application can use the following code.

hMap = CreateFileMapping(...);

if (hMap != NULL && GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMap);
hMap = NULL;
}
return hMap;

Example Code

Creating Named Shared Memory

To share data, multiple processes can use memory-mapped files that are backed by the system paging file.

First Process

The first process creates the file mapping object by calling the CreateFileMapping function with INVALID_HANDLE_VALUE and a name for the object. By using the PAGE_READWRITE flag, the process has read/write permission to the memory through any file views that are created.

Then the process uses the file mapping object handle that CreateFileMapping returns in a call to MapViewOfFile to create a view of the file in the process address space. The MapViewOfFile function returns a pointer to the file view.

When the process does not need access to the file mapping object, it should call the CloseHandle function. When all handles are closed, the system can free the section of the paging file that the object uses.

#include 
#include
#include

#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process");

void main()
{
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // max. object size
BUF_SIZE, // buffer size
szName); // name of mapping object

if (hMapFile == NULL || hMapFile == INVALID_HANDLE_VALUE)
{
printf("Could not create file mapping object (%d).\n",
GetLastError());
return;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);

if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n",
GetLastError());
return;
}


CopyMemory((PVOID)pBuf, szMsg, strlen(szMsg));
getch();

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);
}

Second Process

A second process can access the same data by calling the OpenFileMapping function with the same name as the first process. Then it can use the MapViewOfFile function to obtain a pointer to the file view.

#include 
#include
#include
#include

#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");

void main()
{
HANDLE hMapFile;
LPCTSTR pBuf;

hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object

if (hMapFile == NULL)
{
printf("Could not open file mapping object (%d).\n",
GetLastError());
return;
}

pBuf = MapViewOfFile(hMapFile, // handle to mapping object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);

if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n",
GetLastError());
return;
}

MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

UnmapViewOfFile(pBuf);

CloseHandle(hMapFile);
}

Text Source:MSDN

2008年10月21日 星期二

原來花蓮宜蘭差距這麼遠而且這麼小

今天在搞公司軟體
才發現宜蘭與花蓮的平原如此小
而且群山圍繞難怪交通如此不便
花東縱谷在圖上一目了然
如果國中地理課有這麼好的地圖參考
相信上課會比較有趣吧



2008年9月10日 星期三

何種塑膠可安全使用

因為有實驗研究發現部份塑膠盛裝食物的時候會滲入有毒物質,導致不少人人心惶惶,連食物要怎麼裝都不知道了。

國家地理雜誌的 Green Guide 有鑑於此,特地整理出了一篇文章,詳列哪些塑膠安全,哪些要少用,哪些最好不要用。這裡也轉給大家參考 ^^。

[圖片來源:Popular Science]
聚對苯二甲酸乙二酯(PETE 或 PET)
名字聽起來很厲害,其實就是一般人常說的「保特瓶」(保特瓶其實 就是英文 PET bottle 的翻譯)。保特瓶的材質本身沒有危險,但因為 PET 的結構並不緊密,在縫隙中可能會藏有之前使用時留下來的糖分和隨之而來的細菌,因此並不建議使用超過一次(就是不要當水壺用的意思啦)。

高密度聚乙烯(HDPE)和低密度聚乙烯(LDPE)
聚乙烯在食物保存而言,是最安全的材料之一。不僅沒有任何已知的有毒添加物,而且回收也相對容易,大多數的回收廠都有回收聚乙烯的能力。聚乙烯應用超級廣泛,瓶子、罐子、夾鏈袋、裝蚵仔麵線的那種透明塑膠袋都是。

聚氯乙烯(PVC)危險,非常危險!氯乙烯這個聚乙烯的主要材料本身就是個很危險的有毒物質,有致癌的可能, 再加上聚氯乙烯裡常常有各種添加物、增塑劑,對健康造成不同程度的危害。更慘的是,燃燒 PVC 會產生氯化氫、氯氣和惡名昭彰的有毒物戴奧辛,因此世界各地的環保組織都在建議廢除 PVC 的使用。

聚丙烯(PP)
聚丙烯在化學結構上和聚乙烯類似,因此也是安全的塑膠,大部份的特百惠食品容器都是 PP 或 LDPE製造的,但也有少數是危險的 PC(聚碳酸酯),買之前要看清楚啊!

聚苯乙烯(PS)
聚苯乙烯英文原名Polystyrene,中文依發音翻成「保麗龍」。保麗龍的危險主要來自於它的原料苯乙烯是有毒的,而且聚苯乙烯的化學穩定性比較差,受熱時有可能滲透有毒物質到食物裡。買保麗龍餐盒裝的食物回家後,最好立即換到其他容器內。

聚碳酸酯(PC)、聚乳酸(PLA)等
所有在塑膠分類前六類之外的,全部都分在第七類(怎麼,不會以為前面的 數字是小薑亂寫吧 XD)。在第七類的眾多塑膠中,聚碳酸酯和聚乳酸是比較常見拿來裝食物的材質。聚碳酸酯前面說過了,是一種會釋放類荷爾蒙化合物的危險材質,而一般來拿做 「環保塑膠袋」的聚乳酸則是安全又分解迅速的好朋友。

所以簡單來說,下次買塑膠容器,記得找到塑膠分類回收標誌看一下。如果是「2」、「4」、「5」的話是安全的,「1」最好不要用超過一次,「3」、「6」是危險的,而「7」則要看情況而定。

2008年8月26日 星期二

修正 nVidia 顯示卡驅動程式無法遠端桌面連線問題

GeForce 之前的驅動程式,175.16 / 175.19 / 175.31這三個版本,卻造成一個問題:

Windows XP 的遠端桌面會因為這三個版本的驅動程式而無法使用!
而ASUS EN9600GT 有裝GamerOSD的話則可以遠端桌面連線,但
是連線後遠端電腦的解析度與色彩會變最低,並且無法調整必須重新
開機!

這個問題對沒有在用遠端桌面的人來說,應該都不會發現;但是畢竟有用的人不少,所以還是有引起一些討論。像在官方論壇,就有一串《WHQL 175.16 - remote desktop fails》,是在討論這個問題。不過,目前官方似乎還沒有能解決 175 系列的這個問題?

不過,在該討論串的後面一點,到是有網友有提供解決方案了~他的方法,是去修改 Windows 的 registry:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management]
"SessionImageSize"=dword:00000020

在一般系統裡,預設應該是沒有「SessionImageSize」這個機碼,要自己新增。而據他的說法,這方法是用來增加連線時的影像記憶體大小;其中,0x20 代表的是 32MB,可以自己再調整。


直接下載登錄檔來修正

2008年8月25日 星期一

ASUS EN9600GT/HTDI/512M/A 使用心得(爛)

ASUS EN9600GT/HTDI/512M/A 這塊顯示卡買來使用了一個月(配合P5Q主機版)
我使用遠端桌面連線由A電腦連到B電腦(9600GT裝在B電腦)
當遠端桌面登入B電腦後B電腦的解析度整個變成640×320 4bit color
關閉遠端桌面連線後
在B電腦本地端登入之後B電腦會跳出錯誤訊息 「NVUClockGet」
而且解析度無法再調整了 一定得重開機
拜託這電腦我是拿來架SERVER的 總不能每次遠端登入後就得重新開機吧 =.=
這個問題我在一個月前就打過客服電話了
到現在也沒有解決
今天去ASUS官網下載最新的驅動安裝後還是同樣情形
客服電話0800-093-456寫24H 可是晚上9:30打過去等了5分鍾沒人接
10:30再打過去等了10分鍾還是沒人接
整個FU感覺非常的爛
客服真的該加強
ASUS的驅動程式工程師該換掉 爛透了
奉勸看到此文的朋友顯示卡千萬別買ASUS的阿 一定會後悔死
哀~~~我的五千大洋~~~換來一肚子氣

2008年8月22日 星期五

使用遠端桌面連線複製檔案

  • 從本機電腦複製檔案並貼到遠端電腦上
    1. 按一下 [開始]、[程式集] 或 [所有程式]、按一下 [附屬應用程式],然後按一下 [遠端桌面連線],以開啟 [遠端桌面連線]。
    2. 在 [遠端桌面連線] 對話方塊中,按一下 [選項]。
    3. 按一下 [本機資源] 索引標籤,然後在 [本機裝置和資源] 下,按一下 [其他]。
    4. 按一下 [磁碟機] 旁的加號 (+),選取本機電腦 (您目前使用的電腦) 上要在遠端桌面工作階段中使用的磁碟機,然後按一下 [確定]。
    5. 按一下 [連線],然後建立連線到遠端電腦。
    6. 按一下遠端電腦上的 [開始],然後按一下 [電腦] 或 [我的電腦]。
    7. 當 [電腦] 或 [我的電腦] 在遠端電腦上開啟時,您會看到遠端電腦上的磁碟機以及本機電腦上的磁碟機。下列範例顯示本機電腦上的磁碟機出現在遠端電腦上的 [電腦] 或 [我的電腦] 中時的名稱:C 於 JoesComputer
    8. 在本機電腦上您要轉送到遠端電腦的檔案上按一下滑鼠右鍵,然後按一下 [複製]。
    9. 在相同 [電腦] 或 [我的電腦] 視窗中瀏覽您要在遠端電腦上貼上該檔案的位置。
    10. 在資料夾圖示上按一下滑鼠右鍵,再按 [貼上]。##ReadMore##
  • 從遠端電腦複製檔案並貼到本機電腦上
    1. 按一下 [開始]、[程式集] 或 [所有程式]、按一下 [附屬應用程式],然後按一下 [遠端桌面連線],以開啟 [遠端桌面連線]。
    2. 在 [遠端桌面連線] 對話方塊中,按一下 [選項]。
    3. 按一下 [本機資源] 索引標籤,然後在 [本機裝置和資源] 下,按一下 [其他]。
    4. 按一下 [磁碟機] 旁的加號 (+),選取本機電腦 (您目前使用的電腦) 上要在遠端桌面工作階段中使用的磁碟機,然後按一下 [確定]。
    5. 按一下 [連線],然後建立與遠端電腦間的連線。
    6. 按一下遠端電腦上的 [開始],然後按一下 [電腦] 或 [我的電腦]。
    7. 當 [電腦] 或 [我的電腦] 在遠端電腦上開啟時,您會看到遠端電腦上的磁碟機以及本機電腦上的磁碟機。下列範例顯示本機電腦上的磁碟機出現在遠端電腦上的 [電腦] 或 [我的電腦] 中時的名稱:C on MarysComputer
    8. 在遠端電腦上您要轉送到本機電腦的檔案上按一下滑鼠右鍵,然後按一下 [複製]。
    9. 在相同 [電腦] 或 [我的電腦] 視窗中瀏覽您要在本機電腦上貼上該檔案的位置。
    10. 在資料夾圖示上按一下滑鼠右鍵,再按 [貼上]。

2008年8月21日 星期四

時間格式化函數 strftime

strftime() 函數將時間格式化

我們可以使用strftime()函數將時間格式化為我們想要的格式。它的原型如下:

size_t strftime(

char *strDest,

size_t maxsize,

const char *format,

const struct tm *timeptr

);

我們可以根據format指向字符串中格式命令把timeptr中保存的時間信息放在strDest指向的字符串中,最多向strDest中存放maxsize個字符。該函數返回向strDest指向的字符串中放置的字符數。

函數strftime()的操作有些類似於sprintf():識別以百分號(%)開始的格式命令集合,格式化輸出結果放在一個字符串中。格式化命令說明串 strDest中各種日期和時間信息的確切表示方法。格式串中的其他字符原樣放進串中。格式命令列在下面,它們是區分大小寫的。

%a 星期幾的簡寫

%A 星期幾的全稱

%b 月分的簡寫

%B 月份的全稱

%c 標準的日期的時間串

%C 年份的後兩位數字

%d 十進製表示的每月的第幾天

%D 月/天/年

%e 在兩字符域中,十進製表示的每月的第幾天

%F 年-月-日

%g 年份的後兩位數字,使用基於周的年

%G 年分,使用基於周的年

%h 簡寫的月份名

%H 24小時制的小時

%I 12小時制的小時

%j 十進製表示的每年的第幾天

%m 十進製表示的月份

%M 十時製表示的分鐘數

%n 新行符

%p 本地的AM或PM的等價顯示

%r 12小時的時間

%R 顯示小時和分鐘:hh:mm

%S 十進制的秒數

%t 水平製表符

%T 顯示時分秒:hh:mm:ss

%u 每週的第幾天,星期一為第一天 (值從0到6,星期一為0)

%U 第年的第幾周,把星期日做為第一天(值從0到53)

%V 每年的第幾周,使用基於周的年

%w 十進製表示的星期幾(值從0到6,星期天為0)

%W 每年的第幾周,把星期一做為第一天(值從0到53)

%x 標準的日期串

%X 標準的時間串

%y 不帶世紀的十進制年份(值從0到99)

%Y 帶世紀部分的十制年份

%z,%Z 時區名稱,如果不能得到時區名稱則返回空字符。

%% 百分號

如果想顯示現在是幾點了,並以12小時制顯示,就像下面這段程序:

#include "time.h"

#include "stdio.h"

int main(void)

{

struct tm *ptr;

time_t lt;

char str[80];

lt=time(NULL);

ptr=localtime(<);

strftime(str,100,"It is now %I %p",ptr);

printf(str);

return 0;

}

其運行結果為:

It is now 4PM

而下面的程序則顯示當前的完整日期:

#include

#include

#include

int main( void )

{

struct tm *newtime;

char tmpbuf[128];

time_t lt1;



time( <1 );

newtime=localtime(<1);



strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", newtime);

printf(tmpbuf);



return 0;

}