Список форумов Шадринский форум -> Программирование -> Общие вопросы программирования -> Управление HDD
Начать новую тему   Ответить на тему   вывод темы на печать

Управление HDD

Автор
Сообщение
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.08.22 14:01.36
Ответить с цитатой
Как в Windows программно остановить жесткий диск (чтобы не крутился)? У меня 2 HDD, один малошумящий, в основном обращения к нему идут, а другой шумный. Хочется иметь возможность второй диск останавливать, когда он мне не нужен (а он редко бывает нужен), чтобы при этом первый диск работал постоянно. Поставил настройку "отключать через 3 минуты при отсутствии обращений", но это неудобно, так как отключаются оба диска. Справку по WinAPI изучил, ничего не нашел. Но ведь сама винда как-то их отключает. Как?
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
Slin
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 17.12.2004
Сообщения: 1869


Статус: Offline
СообщениеДобавлено: 2005.08.22 14:13.33
Ответить с цитатой
через дрова... недокументированная возможность...
Посмотреть профиль Отправить личное сообщение ICQ Number
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.08.22 14:41.25
Ответить с цитатой
В линуксе есть сисвызов ioctl(int, int, void*), подозреваю, что он и виндой должен поддерживаться. Узнать бы где описания параметров поподробнее.
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
Slin
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 17.12.2004
Сообщения: 1869


Статус: Offline
СообщениеДобавлено: 2005.08.22 15:12.14
Ответить с цитатой
ты когда-нибудь с символическими именами связывался?
Посмотреть профиль Отправить личное сообщение ICQ Number
andy ice
Militärmagazinkatze


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 23385


Статус: Offline
СообщениеДобавлено: 2005.08.22 16:36.56
Ответить с цитатой
http://msdn.microsoft.com/library/en-us/devio/base/deviceiocontrol.asp

DeviceIoControl

The DeviceIoControl function sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation.


BOOL DeviceIoControl(
HANDLE hDevice,
DWORD dwIoControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped
);

Parameters
hDevice
[in] Handle to the device on which the operation is to be performed. The device is typically a volume, directory, file, or stream. To retrieve a device handle, use the CreateFile function. For more information, see Remarks.
dwIoControlCode
[in] Control code for the operation. This value identifies the specific operation to be performed and the type of device on which to perform it.
For a list of the control codes, see Remarks. The documentation for each control code provides usage details for the lpInBuffer, nInBufferSize, lpOutBuffer, and nOutBufferSize parameters.

lpInBuffer
[in] Pointer to the input buffer that contains the data required to perform the operation. The format of this data depends on the value of the dwIoControlCode parameter.
This parameter can be NULL if dwIoControlCode specifies an operation that does not require input data.

nInBufferSize
[in] Size of the input buffer, in bytes.
lpOutBuffer
[out] Pointer to the output buffer that is to receive the data returned by the operation. The format of this data depends on the value of the dwIoControlCode parameter.
This parameter can be NULL if dwIoControlCode specifies an operation that does not return data.

nOutBufferSize
[in] Size of the output buffer, in bytes.
lpBytesReturned
[out] Pointer to a variable that receives the size of the data stored in the output buffer, in bytes.
If the output buffer is too small to receive any data, the call fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and lpBytesReturned is zero.

If the output buffer is too small to hold all of the data but can hold some entries, some drivers will return as much data as fits. In this case, the call fails, GetLastError returns ERROR_MORE_DATA, and lpBytesReturned indicates the amount of data received. Your application should call DeviceIoControl again with the same operation, specifying a new starting point.

If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an operation returns no output data and lpOutBuffer is NULL, DeviceIoControl makes use of lpBytesReturned. After such an operation, the value of lpBytesReturned is meaningless.

If lpOverlapped is not NULL, lpBytesReturned can be NULL. If this parameter is not NULL and the operation returns data, lpBytesReturned is meaningless until the overlapped operation has completed. To retrieve the number of bytes returned, call GetOverlappedResult. If hDevice is associated with an I/O completion port, you can retrieve the number of bytes returned by calling GetQueuedCompletionStatus.

lpOverlapped
[in] Pointer to an OVERLAPPED structure.
If hDevice was opened without specifying FILE_FLAG_OVERLAPPED, lpOverlapped is ignored.

If hDevice was opened with the FILE_FLAG_OVERLAPPED flag, the operation is performed as an overlapped (asynchronous) operation. In this case, lpOverlapped must point to a valid OVERLAPPED structure that contains a handle to an event object. Otherwise, the function fails in unpredictable ways.

For overlapped operations, DeviceIoControl returns immediately, and the event object is signaled when the operation has been completed. Otherwise, the function does not return until the operation has been completed or an error occurs.

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
To retrieve a handle to the device, you must call the CreateFile function with either the name of a device or the name of the driver associated with a device. To specify a device name, use the following format:

\\.\DeviceName



DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive A: with CreateFile, specify \\.\a:. Alternatively, you can use the names \\.\PhysicalDrive0, \\.\PhysicalDrive1, and so on, to open handles to the physical drives on a system.

Windows Me/98/95: DeviceIoControl can only accept a handle to a virtual device driver. For example, to open a handle to the system VxD with CreateFile, specify \\.\vwin32.


You should specify the FILE_SHARE_READ and FILE_SHARE_WRITE access flags when calling CreateFile to open a handle to a device driver. However, when you open a communications resource, such as a serial port, you must specify exclusive access. Use the other CreateFile parameters as follows when opening a device handle:



The fdwCreate parameter must specify OPEN_EXISTING.
The hTemplateFile parameter must be NULL.
The fdwAttrsAndFlags parameter can specify FILE_FLAG_OVERLAPPED to indicate that the returned handle can be used in overlapped (asynchronous) I/O operations.

For lists of supported control codes, see the following topics:



Communications Control Codes
Device Management Control Codes
Directory Management Control Codes
Disk Management Control Codes
File Management Control Codes
Power Management Control Codes
Volume Management Control Codes

Example Code
For examples that use DeviceIoControl, see the following topics:


Calling DeviceIoControl
Calling DeviceIoControl on Windows Me/98/95

Requirements
Client Requires Windows "Longhorn", Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server "Longhorn", Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header Declared in Winbase.h; include Windows.h.

Library Link to Kernel32.lib.

DLL Requires Kernel32.dll.

See Also
CreateEvent, CreateFile, Device Input and Output Control (IOCTL), GetOverlappedResult, GetQueuedCompletionStatus, OVERLAPPED
_________________
Ин дер гросен фамилие нихт клювен клац-клац Neutral
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
Slin
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 17.12.2004
Сообщения: 1869


Статус: Offline
СообщениеДобавлено: 2005.08.22 16:39.06
Ответить с цитатой
да, andy ice рулит
логично....
Посмотреть профиль Отправить личное сообщение ICQ Number
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.08.22 19:47.24
Ответить с цитатой
Чего логично? Знаю я эту DeviceIoControl, а коды? А хендл диска на 98-й винде? Его ведь CreateFile'ом не достанешь.

Аndy ice, спасибо за источник, почитаю дальше.
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
andy ice
Militärmagazinkatze


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 23385


Статус: Offline
СообщениеДобавлено: 2005.08.22 19:49.42
Ответить с цитатой
там ссылки и всё это там написано.

ps: moishe, поставь себе уже msdn
_________________
Ин дер гросен фамилие нихт клювен клац-клац Neutral
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
Slin
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 17.12.2004
Сообщения: 1869


Статус: Offline
СообщениеДобавлено: 2005.08.22 20:04.57
Ответить с цитатой
логично, что надо msdn юзать, ведь для программеров сделано
Посмотреть профиль Отправить личное сообщение ICQ Number
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.08.22 20:12.31
Ответить с цитатой
Почитал. Прямого ответа не получил. Направление такое: надо добывать хендл VxD vWin32 и пользоваться фактически DOSовским 21-ым прерыванием. Не припомню что-то, чтобы из-под ДОСа можно было диски останавливать...

Следующий вопрос: где взять описание int21h?
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
VolF
подонок


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 3043
Откуда: Rammstein, GmbH

Статус: Offline
СообщениеДобавлено: 2005.08.22 20:26.50
Ответить с цитатой
раздел доков на wasm.ru рулит
покарайне мере раньше рулил
Посмотреть профиль Отправить личное сообщение Посетить сайт автора ICQ Number
Отключение винта
Гость







Статус: Offline
СообщениеДобавлено: 2005.12.09 23:06.40
Ответить с цитатой
Так из драйвера можно отключить питание у винта нумер адын:
mov al, 0xE6
mov dx, 0x1F7
out dx, al
ret
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.12.16 11:00.32
Ответить с цитатой
Спасибо. Есть вопросы:
А как у винта нумер N (N от 1 до 4)?
Из какого драйвера?
Что означают 0xE6 и 0x1F7?
0xE6 - порт винта нумер адын, 0x1F7 - команда отключения питания?
Что будет, если это же самое сделать в приложении?
Какие еще есть команды?
Где о них можно почитать?
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.12.16 13:54.23
Ответить с цитатой
Таки наоборот оказалось: 0x1F7 - порт, а 0xE6 - команда. Ну не знаю я ассемблера...

В Windows 98 работает. Ну а в NT мне и не надо, там DeviceIoControl есть, да и вообще NT я не использую.

Гость "Отключение Винта", как нужный диск-то задать?

P.S. OFF: Классный ник! Вполне в духе "Расщепленный Дуб" и прочие.
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.12.16 19:55.30
Ответить с цитатой
Спасибо вам, Volf и Отключение Винта. Теперь я знаю, как отключить любое из четырех IDE устройств. Я даже написал маленькую программку с названием stop и возможным набором параметров primary/secondary и master/slave. Теперь, чтобы отключить свой диск D, я пишу в консоли
stop secondary master

Проблема решена, вопрос закрыт.
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
char
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1304


Статус: Offline
СообщениеДобавлено: 2005.12.16 21:13.58
Ответить с цитатой
ну так расскажи всем, подсаживай народ на реально полезное программирование Wink
Посмотреть профиль Отправить личное сообщение
moishe
Заслуженный писатель


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 1668


Статус: Offline
СообщениеДобавлено: 2005.12.16 22:08.11
Ответить с цитатой
А рассказывать, собственно, нечего.
/*
 STOP.C
 Остановка жесткого диска
*/

#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define STOP    0xE6 /* команда остановки диска */

int main(int argc,char *argv[]) {
const char *pri="primary";
const char *sec="secondary";
const char *master="master";
const char *slave="slave";
const char *usage="Usage: stop {%s|%s} {%s|%s}\n";
int offset=0;//смещение диапазона ввода-вывода IDE-контроллера
int dev=0;// код выбора устройства master/slave

if(argc!=3) {//проверка синтаксиса
    printf(usage,pri,sec,master,slave);
    return(0);
}
//задаем смещение 0x1F6 для primary и 0x176 для secondary
if(stricmp(argv[1],pri)==0) offset=0x1F6;
else if(stricmp(argv[1],sec)==0) offset=0x176;
if(offset==0) {//первый параметр не primary и не secondary
    printf(usage,pri,sec,master,slave);
    return(0);
}
//задаем код устройства, за него отвечает бит №4; в бите №6 1 = LBA режим
if(stricmp(argv[2],master)==0) dev=0x40;
else if(stricmp(argv[2],slave)==0) dev=0x50;
if(dev==0) {//второй параметр не master и не slave
    printf(usage,pri,sec,master,slave);
    return(0);
}
outp(offset,dev); //выбираем устройство
outp(offset+1,STOP); //останавливаем устройство
return(0);
}


P.S. На wasm.ru раздел доков по-прежнему рулит.
Посмотреть профиль Отправить личное сообщение Отправить e-mail ICQ Number
Leon
Бот-тролль 85 лв


Пол: Пол:Муж.
Зарегистрирован: 25.11.2004
Сообщения: 61661


Статус: Offline
СообщениеДобавлено: 2005.12.18 22:49.08
Ответить с цитатой
moishe писал(а):
На wasm.ru раздел доков по-прежнему рулит.


Никто и не сомневался в этом Wink
_________________
Скажи мне чей Крым, и я скажу кто ты.
Посмотреть профиль Отправить личное сообщение
Страница 1 из 1
Начать новую тему   Ответить на тему   вывод темы на печать
Показать сообщения:   
Список форумов Шадринский форум -> Программирование -> Общие вопросы программирования -> Управление HDD

 
Перейти: 
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете вкладывать файлы
Вы можете скачивать файлы