Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Основная";
Текущий архив: 2006.04.23;
Скачать: [xml.tar.bz2];

Вниз

Проблема при работе двух процессов с одним файлом.   Найти похожие ветки 

 
Ольга   (2006-03-18 15:12) [0]

Отлаживаю чужую программу, не знаю как исправить глюк.
Есть 2 процесса:
Первый - разархивирует файл из директории А в директорию Б.
Второй - сканирует директорию Б на предмет появления нового файла и при его появлении разбирает его.
Есть подозрение, что второй процесс хватает файл, не дождавшись его полного разархивирования. Не знаю как с этим бороться.
Директория сканируется вот таким методом:

ff : TSearchRec;
FindFirst("имя директории Б\*.mpt",faAnyFile-faSysFile-faVolumeID-faDirectory,ff);

(Не понимаю значения аттрибута faVolumeID)
Как задать условие, что не нужно брать файл, который еще занят другим процессом? Или как поставить задержку в программе, чтобы дать файлу полностью записаться?


 
API ©   (2006-03-18 15:17) [1]

Разархивировать в файл под другим именем/расширением. После разархивирования - переименовать в то, что ждет второй поток.


 
Dust ©   (2006-03-18 15:39) [2]

Использовать мьютексы, ждать до тех пор пока второй процесс не освободит мьютекс. после этогозахватывать мьютекс вторым процессом.


 
Ольга   (2006-03-18 15:43) [3]

Что за зверь "мьютекс"? Напишите по-английски, а то мой перевод Help не понимает.


 
Джо ©   (2006-03-18 15:46) [4]

mutex


 
Dust ©   (2006-03-18 15:47) [5]

Взято из MSDN:
CreateMutex
The CreateMutex function creates or opens a named or unnamed mutex object.

HANDLE CreateMutex(
 LPSECURITY_ATTRIBUTES lpMutexAttributes,
 BOOL bInitialOwner,
 LPCTSTR lpName
);

Parameters
lpMutexAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpMutexAttributes is NULL, the handle cannot be inherited.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the new mutex. If lpMutexAttributes is NULL, the mutex gets a default security descriptor. The ACLs in the default security descriptor for a mutex come from the primary or impersonation token of the creator. For more information, see Synchronization Object Security and Access Rights.

bInitialOwner
[in] If this value is TRUE and the caller created the mutex, the calling thread obtains initial ownership of the mutex object. Otherwise, the calling thread does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.
lpName
[in] Pointer to a null-terminated string specifying the name of the mutex object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.
If lpName matches the name of an existing named mutex object, this function requests the MUTEX_ALL_ACCESS access right. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.

If lpName is NULL, the mutex object is created without a name.

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

Terminal Services:  The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces.
Windows XP Home Edition:  Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines 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 4.0 and earlier:  The name can contain any character except the backslash character.
Windows Me/98/95:  The name can contain any character except the backslash character. The empty string ("") is a valid object name.
Return Values
If the function succeeds, the return value is a handle to the mutex object. If the named mutex object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS. Otherwise, the caller created the mutex.

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

WaitForSingleObject

The WaitForSingleObject function returns when one of the following occurs:

The specified object is in the signaled state.
The time-out interval elapses.
To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use the WaitForMultipleObjects.

DWORD WaitForSingleObject(
 HANDLE hHandle,
 DWORD dwMilliseconds
);

Parameters
hHandle
[in] Handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section.
If this handle is closed while the wait is still pending, the function"s behavior is undefined.

The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights.

dwMilliseconds
[in] Time-out interval, in milliseconds. The function returns if the interval elapses, even if the object"s state is nonsignaled. If dwMilliseconds is zero, the function tests the object"s state and returns immediately. If dwMilliseconds is INFINITE, the function"s time-out interval never elapses.
Return Values
If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values.

Return Code Description
WAIT_ABANDONED The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread, and the mutex is set to nonsignaled.
WAIT_OBJECT_0 The state of the specified object is signaled.
WAIT_TIMEOUT The time-out interval elapsed, and the object"s state is nonsignaled.

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

Remarks
The WaitForSingleObject function checks the current state of the specified object. If the object"s state is nonsignaled, the calling thread enters the wait state. It uses no processor time while waiting for the object state to become signaled or the time-out interval to elapse.

The function modifies the state of some types of synchronization objects. Modification occurs only for the object whose signaled state caused the function to return. For example, the count of a semaphore object is decreased by one.

The WaitForSingleObject function can wait for the following objects:

Change notification
Console input
Event
Job
Memory resource notification
Mutex
Process
Semaphore
Thread
Waitable timer

Use caution when calling the wait functions and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. A thread that uses a wait function with no time-out interval may cause the system to become deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject.

For more information, see Using Mutex Objects.

Requirements
Client: Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.


 
Dust ©   (2006-03-18 15:49) [6]

ReleaseMutex

The ReleaseMutex function releases ownership of the specified mutex object.

BOOL ReleaseMutex(
 HANDLE hMutex
);

Parameters
hMutex
[in] Handle to the mutex object. The CreateMutex or OpenMutex function returns this handle.
The handle must have the MUTEX_MODIFY_STATE access right. For more information, see Synchronization Object Security and Access Rights.

Return Values
If the function succeeds, the return value is nonzero.

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

Remarks
The ReleaseMutex function fails if the calling thread does not own the mutex object.

A thread gets ownership of a mutex by specifying a handle to the mutex in one of the wait functions. The thread that creates a mutex object can also get immediate ownership without using one of the wait functions. When the owning thread no longer needs to own the mutex object, it calls the ReleaseMutex function.

While a thread has ownership of a mutex, it can specify the same mutex in additional wait-function calls without blocking its execution. This prevents a thread from deadlocking itself while waiting for a mutex that it already owns. However, to release its ownership, the thread must call ReleaseMutex once for each time that the mutex satisfied a wait.


 
Джо ©   (2006-03-18 15:50) [7]

> Dust

Ты собрался сюда весь MSDN скопипастить? ;>


 
Dust ©   (2006-03-18 15:54) [8]

Нет, я думаю  в данной теме (по синхронизации доступа к объектам), описание функций и объектов синхронизации не сильно помешает.
Тем паче, что по большей части народ вообще никак не юзает объекты синхронизации.


 
Dust ©   (2006-03-18 15:55) [9]

статью написать чтоли...



Страницы: 1 вся ветка

Форум: "Основная";
Текущий архив: 2006.04.23;
Скачать: [xml.tar.bz2];

Наверх




Память: 0.49 MB
Время: 0.011 c
2-1144724162
Laymer
2006-04-11 06:56
2006.04.23
FastReport


2-1144323969
Скиф
2006-04-06 15:46
2006.04.23
Как осуществить перезагрузку Windows


1-1142875448
KALqYAN
2006-03-20 20:24
2006.04.23
Picture Change...


15-1144160567
Volf_555
2006-04-04 18:22
2006.04.23
Как подлкючить человека? Живёт от меня на расстоянии ~130 м


15-1143814893
Tonich
2006-03-31 18:21
2006.04.23
C++





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский