«Child Process» и «Windows terminal server»: разница между страницами

Материал из support.qbpro.ru
(Различия между страницами)
imported>Supportadmin
 
imported>Vix
Нет описания правки
 
Строка 1: Строка 1:
'''''Stability: 3 - Stable'''''
== Оптимизация Windows terminal server ==
'''В данной статье рассматривается возможность оптимизации работы терминального сервера на платформе Windows. Данные рекомендации использовались на версиях Windows XP и Windows 2003. Возможно будут работать на Windows 7.'''  
*подразумевается, что вы уже установили сервер терминалов, он у вас работает и все дальнейшие действия выполняются на рабочем сервере. При этом категорически рекомендуем делать bakup изменений реестра или изменяемых системных файлов.


Node обеспечивает трёх-направленный POPEN (3) для модуля child_process.
*Рекомендация для правильной работы спулера принтеров сервера, данная операция производится после установки всех необходимых драйверов принтеров.
Сообщения об ошибках из-за проблем с монитором локального порта
После перезагрузки компьютера или после перезапуска службы «Диспетчер очереди печати» появляется следующее сообщение об ошибке:
Сбой при запуске Spoolsv.exe
Если открыть окно свойств принтера, появляется следующее сообщение об ошибке:
Недостаточно ресурсов
При попытке печати документа появляется сообщение об ошибке «Нарушение прав доступа» (программа Dr. Watson). В журнале программы
Dr. Watson присутствует запись об ошибке в программе Spoolsv.exe с кодом ошибки C0000005.
Появляется следующее сообщение об ошибке и диспетчер очереди печати останавливается:
Инструкция по адресу 'адрес' обратилась к памяти по адресу 'адрес'. Память не может быть «read».
Такое же сообщение появляется при попытке перезапуска службы «Диспетчер очереди печати» и при открытии папки «Принтеры».
Причиной проблемы может являться то, что используемый по умолчанию монитор локального порта заменен программой независимого
производителя. Чтобы устранить ошибку, необходимо внести изменения в системный реестр.
*Для этого выполните следующие действия.
Откройте редактор реестра.
2. Найдите параметр Local Port в следующем разделе реестра.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Local Port
3. Дважды щелкните параметр Driver и измените его значение. Введите строковое значение Localspl.dll и нажмите кнопку ОК.
4. Проверьте, присутствуют ли мониторы независимых производителей в следующем разделе реестра. Удалите все мониторы,
кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors
По умолчанию используются следующие мониторы.
AppleTalk Printing Devices (присутствует, если установлены службы для Macintosh)
BJ Language Monitor
Local Port
PJL Language Monitor
Standard TCP/IP Port
USB Monitor
Windows NT Fax Monitor


Поток данных можно направлять через стандартные stdin, stdout и stderr дочернего процесса в полностью неблокирующем стиле. (Заметим, что некоторые программы используют внутреннюю линейную буферизации строк ввода/вывода. Это не влияет node.js, но это означает что информация, передаваемая дочернему процессу "потребляется" им не сразу.)
** LPR Port
Примечание. Удаление монитора LPR Port должно выполняться только по рекомендации специалиста службы технической поддержки
корпорации Майкрософт.
5. Проверьте, присутствуют ли службы печати сторонних производителей в следующем разделе реестра. Удалите все службы печати,
кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Providers
По умолчанию используется следующие службы печати.
Internet Print Provider
LanMan Print Services
6. Проверьте, присутствуют ли обработчики печати сторонних производителей в следующем разделе реестра. Удалите все обработчики
печати, кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\Print Processors
По умолчанию используется следующий обработчик печати
WinPrint
Чтобы определить обработчик печати, используемый принтером, с помощью средства MPS_REPORTS (Microsoft Product Support Reporting Tool)
откройте файл MachineName_PRINTDRIVERS.TXT и найдите в нем нужный обработчик печати независимого производителя и очереди, которые
его используют.  
7. Замените обработчик печати независимого производителя обработчиком WinPrint.
8. Нажмите кнопку Пуск и выберите в меню Настройка пункт Панель управления.
9. Дважды щелкните значок Принтеры, щелкните правой кнопкой мыши нужный принтер и выберите команду Свойства.
10. Перейдите на вкладку Дополнительно и нажмите кнопку Обработчик печати.
11. В списке Обработчик печати выберите WinPrint.
12. Дважды нажмите кнопку ОК.
13. Закройте редактор реестра.


Для создания дочернего процесса используйте require('child_process').spawn() или require('child_process').fork(). Семантика каждого немного отличается, и описана ниже.
После внесения изменений в реестр перезапустите диспетчер очереди печати. Для этого запустите консоль управления (MMC)
и добавьте оснастки «Управление компьютером» или «Службы». Щелкните правой кнопкой мыши службу Диспетчер очереди печати
и выберите команду Пуск.


==Class: ChildProcess==
*При переполнении за сутки очереди печати чистим батником:
ChildProcess is an EventEmitter.


Child processes always have three streams associated with them. child.stdin, child.stdout, and child.stderr. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from.
@echo off
net stop spooler
echo y|del C:\WINDOWS\system32\spool\PRINTERS\*
net start spooler


The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a Child Process instance.
*При печати клиента из терминального режима на локальный принтер в системном логе сервера появляется сообщение об ошибке:
Event ID: 1103 Description: An internal communication error occurred. Решение проблемы:
Это происходит, если имя принтера на рабочей станции не совпадает с именем
принтера на терминал-сервере. Как правило, это бывает, если в качестве клиента
используются компьютеры под управлением Windows 95/98/Me. Запишите название
принтера на рабочей станции в локальном режиме, затем начните установку этого
принтера на терминал-сервере и снова запишите его название. Затем откройте
файл %systemroot%\system32\Wtsuprn.txt и добавьте в него свой принтер. Уберите
значек комментария перед вносимой строкой, а полученный файл сохраните под
именем %systemroot%\system32\Wtsuprn.inf.
('''или скачайте этот файл тут:''' http://nixtech.ru/datatrans/win32/term-prn/wtsuprn.txt)
('''или тут:''' http://support.citrix.com/article/CTX626451)
log on на терминал-сервере. Затем подключитесь с клиентской рабочей станции. Ваш принтер
должен автоматически появится в папке Printers терминальной сессии.
('''Инструкция от Microsoft по установке''' http://support.microsoft.com/kb/214593)


===Event: 'error'===
*Полезные ссылки по решению проблем печати на терминальном сервере
err Error Object the error.
('''Решение проблем печати в терминальных сетях и терминальных службах.''' http://admin-dm.livejournal.com/67401.html)
Emitted when:


The process could not be spawned, or
('''Совместимость имен принтеров при работе с терминальным сервером''' http://support.citrix.com/article/CTX626451)
The process could not be killed, or
Sending a message to the child process failed for whatever reason.
See also ChildProcess#kill() and ChildProcess#send().


===Event: 'exit'===
('''Terminal Server Printer Redirection Wizard Tool''' http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=5640)
code Number the exit code, if it exited normally.
signal String the signal passed to kill the child process, if it was killed by the parent.
This event is emitted after the child process ends. If the process terminated normally, code is the final exit code of the process, otherwise null. If the process terminated due to receipt of a signal, signal is the string name of the signal, otherwise null.


Note that the child process stdio streams might still be open.
*Патч для увеличения максимального количества полуоткрытых соединений
Впервые данное ограничение было введено компанией Microsoft в SP2 (Service Pack 2) для Windows XP и присутствует в последующих
версиях Windows.
Это было сделано в попытке замедлить распространение вирусов с зараженного компьютера, а также ограничить возможности участия
компьютера в DoS-атаках (от англ. Denial of Service, отказ в обслуживании).
Ограничение заключается в том, что компьютеру не разрешается иметь более 10 одновременных полуоткрытых исходящих соединений.
При достижении предела новые попытки подключений ставятся в очередь. Таким образом, фактически ограничена скорость подключения
к другим компьютерам.
('''Патч Half-open limit fix''' http://half-open.com/download_ru.htm) позволяет убрать это ограничение, то есть увеличить
максимальный предел полуоткрытых соединений. Для подавляющего большинства пользователей будет достаточным предел, равный 100


See waitpid(2).
*Оптимизация работы клиента на медленном канале:
'''Цельный курсор'''
Установка курсора немигающим очень эффективно в низкоскоростных соединениях. Мерцающий курсор посылает несколько байт
данных при каждом мерцании, и запрет мерцания экономит немного полосы пропускания.
HKEY_USERS/.default/Control Panel/Desktop
Установите значение CursorBlinkRate Reg_SZ -1 (1200)
'''Скорость обновления меню Start'''
Вы можете увеличить скорость обновления, чтобы уменьшить время ответа в меню.
"HKEY_USERS\DEFAULT\Control Panel\Desktop"
Добавьте значение: MenuShowDelay REG_DWORD: 10 (400)


===Event: 'close'===
*Полезные советы и ссылки:
code Number the exit code, if it exited normally.
('''Решение проблем с терминальным сервером и не только''' http://adsh.ukrweb.net/win2k/fido_faq_10.html)
signal String the signal passed to kill the child process, if it was killed by the parent.
This event is emitted when the stdio streams of a child process have all terminated. This is distinct from 'exit', since multiple processes might share the same stdio streams.


===Event: 'disconnect'===
*Без перезагрузки компьютера средствами командной строки, как правило, не обходится ни один диск автоматической установки Windows - это завершающая процедура, после которой компьютер уже готов к использованию. Перезагрузить компьютер можно различными способами.
This event is emitted after using the .disconnect() method in the parent or in the child. After disconnecting it is no longer possible to send messages. An alternative way to check if you can send messages is to see if the child.connected property is true.
Команда shutdown


===Event: 'message'===
    shutdown.exe -r -f -t 20 -c "Don`t panic. The system will reboot in 20 seconds."
message Object a parsed JSON object or primitive value
sendHandle Handle object a Socket or Server object
Messages send by .send(message, [sendHandle]) are obtained using the message event.


====child.stdin====
Справка: shutdown /?
Stream object
A Writable Stream that represents the child process's stdin. Closing this stream via end() often causes the child process to terminate.


If the child stdio streams are shared with the parent, then this will not be set.
* управление screensaver в терминальном сервере
[http://amaksimov.wordpress.com/2011/10/15/computer-block-lock-out-via-screen-saver-timeout-and-password-protect-with-gpp-group-policy-preferences/ screensaver в терминальном сервере]


====child.stdout====
'''944984 - на сервере стоит SP2 который уже идет с User Profile Hive Cleanup'''
Stream object
  Service (UPHClean).  
A Readable Stream that represents the child process's stdout.
  906952 -  на сервере отключен мап любых принтеров и остального,
  кроме дисков (флешки и флопы мапить), там отмечено, что эта проблема была учтена в SP2. Также
  там написано, что ее включить надо, так вот этот момент немного не понятен:


If the child stdio streams are shared with the parent, then this will not be set.
  To enable this hotfix, you must create the PrinterMaskKey registry subkey. To do
  this, follow these steps:


====child.stderr====
  1. Click Start, click Run, type regedit, and then click OK.
Stream object
  2. Locate the following registry subkey:
A Readable Stream that represents the child process's stderr.
  HKEY_USERS\.default\printers
  3. Right-click the registry subkey that you located in step 2, point to New,
  click Key, type PrinterMaskKey, and then press ENTER.
  4. Exit Registry Editor.
  Что конкретно нужно создать в ветке HKEY_USERS\.default\printers, если не
  трудно, поясните?
  '''''--В локаликозованной версии regedit Key = Раздел Т.е. надо создать подраздел
  PrinterMaskKey внутри HKEY_USERS\.default\printers'''''


If the child stdio streams are shared with the parent, then this will not be set.
[[Hotfix - terminal server win]]


====child.pid====
== Настройка меню пользователя в Win2003 ==
'''Integer'''
*как скрыть пункт в меню Пуск - Администрирование, от терминальных пользователей?


The PID of the child process.
В групповых политиках, конфигурации пользователя, административных шаблонах, в настройках меню "Пуск" отключите необходимые элементы.


Example:
Пример:


<nowiki>var spawn = require('child_process').spawn,
Конфигурация пользователя -> Настройка -> Параметры панели управления -> Главное меню
    grep  = spawn('grep', ['ssh']);


console.log('Spawned child pid: ' + grep.pid);
[[Файл:Win2008adm.jpg]]
grep.stdin.end();</nowiki>
====child.kill([signal])====
'''signal String'''
 
Send a signal to the child process. If no argument is given, the process will be sent 'SIGTERM'. See signal(7) for a list of available signals.
 
<nowiki>var spawn = require('child_process').spawn,
    grep  = spawn('grep', ['ssh']);
 
grep.on('close', function (code, signal) {
  console.log('child process terminated due to receipt of signal '+signal);
});
 
// send SIGHUP to process
grep.kill('SIGHUP');</nowiki>
 
May emit an 'error' event when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyone's guess.
 
Note that while the function is called kill, the signal delivered to the child process may not actually kill it. kill really just sends a signal to a process.
 
See kill(2)
 
====child.send(message, [sendHandle])====
'''message Object'''
 
'''sendHandle Handle object'''
 
When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.
 
For example:
 
<nowiki>var cp = require('child_process');
 
var n = cp.fork(__dirname + '/sub.js');
 
n.on('message', function(m) {
  console.log('PARENT got message:', m);
});
 
n.send({ hello: 'world' });</nowiki>
And then the child script, 'sub.js' might look like this:
 
<nowiki>process.on('message', function(m) {
  console.log('CHILD got message:', m);
});
 
process.send({ foo: 'bar' });</nowiki>
In the child the process object will have a send() method, and process will emit objects each time it receives a message on its channel.
 
There is a special case when sending a {cmd: 'NODE_foo'} message. All messages containing a NODE_ prefix in its cmd property will not be emitted in the message event, since they are internal messages used by node core. Messages containing the prefix are emitted in the internalMessage event, you should by all means avoid using this feature, it is subject to change without notice.
 
The sendHandle option to child.send() is for sending a TCP server or socket object to another process. The child will receive the object as its second argument to the message event.
 
Emits an 'error' event if the message cannot be sent, for example because the child process has already exited.
 
====Example: sending server object====
 
Here is an example of sending a server:
 
<nowiki>var child = require('child_process').fork('child.js');
 
// Open up the server object and send the handle.
var server = require('net').createServer();
server.on('connection', function (socket) {
  socket.end('handled by parent');
});
server.listen(1337, function() {
  child.send('server', server);
});</nowiki>
And the child would the receive the server object as:
 
<nowiki>process.on('message', function(m, server) {
  if (m === 'server') {
    server.on('connection', function (socket) {
      socket.end('handled by child');
    });
  }
});</nowiki>
 
Note that the server is now shared between the parent and child, this means that some connections will be handled by the parent and some by the child.
 
For dgram servers the workflow is exactly the same. Here you listen on a message event instead of connection and use server.bind instead of server.listen. (Currently only supported on UNIX platforms.)
 
====Example: sending socket object====
 
Here is an example of sending a socket. It will spawn two children and handle connections with the remote address 74.125.127.100 as VIP by sending the socket to a "special" child process. Other sockets will go to a "normal" process.
 
<nowiki>var normal = require('child_process').fork('child.js', ['normal']);
var special = require('child_process').fork('child.js', ['special']);
 
// Open up the server and send sockets to child
var server = require('net').createServer();
server.on('connection', function (socket) {
 
  // if this is a VIP
  if (socket.remoteAddress === '74.125.127.100') {
    special.send('socket', socket);
    return;
  }
  // just the usual dudes
  normal.send('socket', socket);
});
server.listen(1337);</nowiki>
The child.js could look like this:
 
<nowiki>process.on('message', function(m, socket) {
  if (m === 'socket') {
    socket.end('You were handled as a ' + process.argv[2] + ' person');
  }
});</nowiki>
Note that once a single socket has been sent to a child the parent can no longer keep track of when the socket is destroyed. To indicate this condition the .connections property becomes null. It is also recommended not to use .maxConnections in this condition.
 
===child.disconnect()===
To close the IPC connection between parent and child use the child.disconnect() method. This allows the child to exit gracefully since there is no IPC channel keeping it alive. When calling this method the disconnect event will be emitted in both parent and child, and the connected flag will be set to false. Please note that you can also call process.disconnect() in the child process.
 
===child_process.spawn(command, [args], [options])===
command String The command to run
 
args Array List of string arguments
 
options Object
 
cwd String Current working directory of the child process
stdio Array|String Child's stdio configuration. (See below)
customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
env Object Environment key-value pairs
detached Boolean The child will be a process group leader. (See below)
uid Number Sets the user identity of the process. (See setuid(2).)
gid Number Sets the group identity of the process. (See setgid(2).)
return: ChildProcess object
Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
 
The third argument is used to specify additional options, which defaults to:
 
{ cwd: undefined,
  env: process.env
}
cwd allows you to specify the working directory from which the process is spawned. Use env to specify environment variables that will be visible to the new process.
 
Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:
 
var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);
 
ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});
 
ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});
 
ls.on('close', function (code) {
  console.log('child process exited with code ' + code);
});
Example: A very elaborate way to run 'ps ax | grep ssh'
 
var spawn = require('child_process').spawn,
    ps    = spawn('ps', ['ax']),
    grep  = spawn('grep', ['ssh']);
 
ps.stdout.on('data', function (data) {
  grep.stdin.write(data);
});
 
ps.stderr.on('data', function (data) {
  console.log('ps stderr: ' + data);
});
 
ps.on('close', function (code) {
  if (code !== 0) {
    console.log('ps process exited with code ' + code);
  }
  grep.stdin.end();
});
 
grep.stdout.on('data', function (data) {
  console.log('' + data);
});
 
grep.stderr.on('data', function (data) {
  console.log('grep stderr: ' + data);
});
 
grep.on('close', function (code) {
  if (code !== 0) {
    console.log('grep process exited with code ' + code);
  }
});
Example of checking for failed exec:
 
var spawn = require('child_process').spawn,
    child = spawn('bad_command');
 
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
  if (/^execvp\(\)/.test(data)) {
    console.log('Failed to start child process.');
  }
});
Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than using process.env. This due to backwards compatibility issues with a deprecated API.
 
The 'stdio' option to child_process.spawn() is an array where each index corresponds to a fd in the child. The value is one of the following:
 
'pipe' - Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the child_process object as ChildProcess.stdio[fd]. Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.
'ipc' - Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the ChildProcess.send() method. If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on('message'). If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on('message').
'ignore' - Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns. When any of these is ignored node will open /dev/null and attach it to the child's fd.
Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array.
Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process. It is shared with the child process, similar to how Stream objects can be shared.
null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is 'ignore'.
As a shorthand, the stdio argument may also be one of the following strings, rather than an array:
 
ignore - ['ignore', 'ignore', 'ignore']
pipe - ['pipe', 'pipe', 'pipe']
inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
Example:
 
var spawn = require('child_process').spawn;
 
// Child will use parent's stdios
spawn('prg', [], { stdio: 'inherit' });
 
// Spawn child sharing only stderr
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
 
// Open an extra fd=4, to interact with programs present a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
If the detached option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.
 
By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given child, use the child.unref() method, and the parent's event loop will not include the child in its reference count.
 
Example of detaching a long-running process and redirecting its output to a file:
 
var fs = require('fs'),
    spawn = require('child_process').spawn,
    out = fs.openSync('./out.log', 'a'),
    err = fs.openSync('./out.log', 'a');
 
var child = spawn('prg', [], {
  detached: true,
  stdio: [ 'ignore', out, err ]
});
 
child.unref();
When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.
 
There is a deprecated option called customFds which allows one to specify specific file descriptors for the stdio of the child process. This API was not portable to all platforms and therefore removed. With customFds it was possible to hook up the new process' [stdin, stdout, stderr] to existing streams; -1 meant that a new stream should be created. Use at your own risk.
 
See also: child_process.exec() and child_process.fork()
 
child_process.exec(command, [options], callback)#
command String The command to run, with space-separated arguments
options Object
cwd String Current working directory of the child process
env Object Environment key-value pairs
encoding String (Default: 'utf8')
timeout Number (Default: 0)
maxBuffer Number (Default: 200*1024)
killSignal String (Default: 'SIGTERM')
callback Function called with the output when process terminates
error Error
stdout Buffer
stderr Buffer
Return: ChildProcess object
Runs a command in a shell and buffers the output.
 
var exec = require('child_process').exec,
    child;
 
child = exec('cat *.js bad_file | wc -l',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});
The callback gets the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error and err.code will be the exit code of the child process, and err.signal will be set to the signal that terminated the process.
 
There is a second optional argument to specify several options. The default options are
 
{ encoding: 'utf8',
  timeout: 0,
  maxBuffer: 200*1024,
  killSignal: 'SIGTERM',
  cwd: null,
  env: null }
If timeout is greater than 0, then it will kill the child process if it runs longer than timeout milliseconds. The child process is killed with killSignal (default: 'SIGTERM'). maxBuffer specifies the largest amount of data allowed on stdout or stderr - if this value is exceeded then the child process is killed.
 
child_process.execFile(file, args, options, callback)#
file String The filename of the program to run
args Array List of string arguments
options Object
cwd String Current working directory of the child process
env Object Environment key-value pairs
encoding String (Default: 'utf8')
timeout Number (Default: 0)
maxBuffer Number (Default: 200*1024)
killSignal String (Default: 'SIGTERM')
callback Function called with the output when process terminates
error Error
stdout Buffer
stderr Buffer
Return: ChildProcess object
This is similar to child_process.exec() except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than child_process.exec. It has the same options.
 
child_process.fork(modulePath, [args], [options])#
modulePath String The module to run in the child
args Array List of string arguments
options Object
cwd String Current working directory of the child process
env Object Environment key-value pairs
encoding String (Default: 'utf8')
execPath String Executable used to create the child process
Return: ChildProcess object
This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See child.send(message, [sendHandle]) for details.
 
By default the spawned Node process will have the stdout, stderr associated with the parent's. To change this behavior set the silent property in the options object to true.
 
The child process does not automatically exit once it's done, you need to call process.exit() explicitly. This limitation may be lifted in the future.
 
These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them.
 
The execPath property in the options object allows for a process to be created for the child rather than the current node executable. This should be done with care and by default will talk over the fd represented an environmental variable NODE_CHANNEL_FD on the child process. The input and output on this fd is expected to be line delimited JSON objects.

Версия от 01:51, 9 сентября 2013

Оптимизация Windows terminal server

В данной статье рассматривается возможность оптимизации работы терминального сервера на платформе Windows. Данные рекомендации использовались на версиях Windows XP и Windows 2003. Возможно будут работать на Windows 7.

  • подразумевается, что вы уже установили сервер терминалов, он у вас работает и все дальнейшие действия выполняются на рабочем сервере. При этом категорически рекомендуем делать bakup изменений реестра или изменяемых системных файлов.
  • Рекомендация для правильной работы спулера принтеров сервера, данная операция производится после установки всех необходимых драйверов принтеров.
Сообщения об ошибках из-за проблем с монитором локального порта
После перезагрузки компьютера или после перезапуска службы «Диспетчер очереди печати» появляется следующее сообщение об ошибке: 
Сбой при запуске Spoolsv.exe
Если открыть окно свойств принтера, появляется следующее сообщение об ошибке: 
Недостаточно ресурсов
При попытке печати документа появляется сообщение об ошибке «Нарушение прав доступа» (программа Dr. Watson). В журнале программы
Dr. Watson присутствует запись об ошибке в программе Spoolsv.exe с кодом ошибки C0000005. 
Появляется следующее сообщение об ошибке и диспетчер очереди печати останавливается: 
Инструкция по адресу 'адрес' обратилась к памяти по адресу 'адрес'. Память не может быть «read». 
Такое же сообщение появляется при попытке перезапуска службы «Диспетчер очереди печати» и при открытии папки «Принтеры». 
Причиной проблемы может являться то, что используемый по умолчанию монитор локального порта заменен программой независимого
производителя. Чтобы устранить ошибку, необходимо внести изменения в системный реестр. 
  • Для этого выполните следующие действия.
Откройте редактор реестра.
2. Найдите параметр Local Port в следующем разделе реестра. 
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Local Port
3. Дважды щелкните параметр Driver и измените его значение. Введите строковое значение Localspl.dll и нажмите кнопку ОК.
4. Проверьте, присутствуют ли мониторы независимых производителей в следующем разделе реестра. Удалите все мониторы, 
кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors
По умолчанию используются следующие мониторы. 
AppleTalk Printing Devices (присутствует, если установлены службы для Macintosh)
BJ Language Monitor
Local Port
PJL Language Monitor
Standard TCP/IP Port
USB Monitor
Windows NT Fax Monitor
** LPR Port
Примечание. Удаление монитора LPR Port должно выполняться только по рекомендации специалиста службы технической поддержки
корпорации Майкрософт. 
5. Проверьте, присутствуют ли службы печати сторонних производителей в следующем разделе реестра. Удалите все службы печати,
кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Providers
По умолчанию используется следующие службы печати. 
Internet Print Provider
LanMan Print Services
6. Проверьте, присутствуют ли обработчики печати сторонних производителей в следующем разделе реестра. Удалите все обработчики
печати, кроме используемых по умолчанию.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Environments\Windows NT x86\Print Processors 
По умолчанию используется следующий обработчик печати
WinPrint 
Чтобы определить обработчик печати, используемый принтером, с помощью средства MPS_REPORTS (Microsoft Product Support Reporting Tool)
откройте файл MachineName_PRINTDRIVERS.TXT и найдите в нем нужный обработчик печати независимого производителя и очереди, которые
его используют. 
7. Замените обработчик печати независимого производителя обработчиком WinPrint.
8. Нажмите кнопку Пуск и выберите в меню Настройка пункт Панель управления.
9. Дважды щелкните значок Принтеры, щелкните правой кнопкой мыши нужный принтер и выберите команду Свойства.
10. Перейдите на вкладку Дополнительно и нажмите кнопку Обработчик печати.
11. В списке Обработчик печати выберите WinPrint.
12. Дважды нажмите кнопку ОК.
13. Закройте редактор реестра.
После внесения изменений в реестр перезапустите диспетчер очереди печати. Для этого запустите консоль управления (MMC)
и добавьте оснастки «Управление компьютером» или «Службы». Щелкните правой кнопкой мыши службу Диспетчер очереди печати
и выберите команду Пуск.
  • При переполнении за сутки очереди печати чистим батником:
@echo off 
net stop spooler 
echo y|del C:\WINDOWS\system32\spool\PRINTERS\*
net start spooler
  • При печати клиента из терминального режима на локальный принтер в системном логе сервера появляется сообщение об ошибке:
Event ID: 1103 Description: An internal communication error occurred. Решение проблемы:
Это происходит, если имя принтера на рабочей станции не совпадает с именем 
принтера на терминал-сервере. Как правило, это бывает, если в качестве клиента
используются компьютеры под управлением Windows 95/98/Me. Запишите название 
принтера на рабочей станции в локальном режиме, затем начните установку этого 
принтера на терминал-сервере и снова запишите его название. Затем откройте 
файл %systemroot%\system32\Wtsuprn.txt и добавьте в него свой принтер. Уберите 
значек комментария перед вносимой строкой, а полученный файл сохраните под 
именем %systemroot%\system32\Wtsuprn.inf. 
(или скачайте этот файл тут: http://nixtech.ru/datatrans/win32/term-prn/wtsuprn.txt)
(или тут: http://support.citrix.com/article/CTX626451)
log on на терминал-сервере. Затем подключитесь с клиентской рабочей станции. Ваш принтер 
должен автоматически появится в папке Printers терминальной сессии.
(Инструкция от Microsoft по установке http://support.microsoft.com/kb/214593)
  • Полезные ссылки по решению проблем печати на терминальном сервере

(Решение проблем печати в терминальных сетях и терминальных службах. http://admin-dm.livejournal.com/67401.html)

(Совместимость имен принтеров при работе с терминальным сервером http://support.citrix.com/article/CTX626451)

(Terminal Server Printer Redirection Wizard Tool http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=5640)

  • Патч для увеличения максимального количества полуоткрытых соединений
Впервые данное ограничение было введено компанией Microsoft в SP2 (Service Pack 2) для Windows XP и присутствует в последующих 
версиях Windows.
Это было сделано в попытке замедлить распространение вирусов с зараженного компьютера, а также ограничить возможности участия 
компьютера в DoS-атаках (от англ. Denial of Service, отказ в обслуживании). 
Ограничение заключается в том, что компьютеру не разрешается иметь более 10 одновременных полуоткрытых исходящих соединений. 
При достижении предела новые попытки подключений ставятся в очередь. Таким образом, фактически ограничена скорость подключения
к другим компьютерам.
(Патч Half-open limit fix http://half-open.com/download_ru.htm) позволяет убрать это ограничение, то есть увеличить 
максимальный предел полуоткрытых соединений. Для подавляющего большинства пользователей будет достаточным предел, равный 100
  • Оптимизация работы клиента на медленном канале:
Цельный курсор
Установка курсора немигающим очень эффективно в низкоскоростных соединениях. Мерцающий курсор посылает несколько байт 
данных при каждом мерцании, и запрет мерцания экономит немного полосы пропускания.
HKEY_USERS/.default/Control Panel/Desktop
Установите значение CursorBlinkRate Reg_SZ -1 (1200)
Скорость обновления меню Start
Вы можете увеличить скорость обновления, чтобы уменьшить время ответа в меню.
"HKEY_USERS\DEFAULT\Control Panel\Desktop"
Добавьте значение: MenuShowDelay REG_DWORD: 10 (400)
  • Полезные советы и ссылки:
(Решение проблем с терминальным сервером и не только http://adsh.ukrweb.net/win2k/fido_faq_10.html)
  • Без перезагрузки компьютера средствами командной строки, как правило, не обходится ни один диск автоматической установки Windows - это завершающая процедура, после которой компьютер уже готов к использованию. Перезагрузить компьютер можно различными способами.

Команда shutdown

   shutdown.exe -r -f -t 20 -c "Don`t panic. The system will reboot in 20 seconds."

Справка: shutdown /?

  • управление screensaver в терминальном сервере

screensaver в терминальном сервере

944984 - на сервере стоит SP2 который уже идет с User Profile Hive Cleanup

 Service (UPHClean). 
 906952 -  на сервере отключен мап любых принтеров и остального,
 кроме дисков (флешки и флопы мапить), там отмечено, что эта проблема была учтена в SP2. Также
 там написано, что ее включить надо, так вот этот момент немного не понятен:
 To enable this hotfix, you must create the PrinterMaskKey registry subkey. To do
 this, follow these steps:
 1. Click Start, click Run, type regedit, and then click OK.
 2. Locate the following registry subkey:
 HKEY_USERS\.default\printers
 3. Right-click the registry subkey that you located in step 2, point to New,
 click Key, type PrinterMaskKey, and then press ENTER.
 4. Exit Registry Editor.
 Что конкретно нужно создать в ветке HKEY_USERS\.default\printers, если не
 трудно, поясните?
 --В локаликозованной версии regedit Key = Раздел Т.е. надо создать подраздел
 PrinterMaskKey внутри HKEY_USERS\.default\printers

Hotfix - terminal server win

Настройка меню пользователя в Win2003

  • как скрыть пункт в меню Пуск - Администрирование, от терминальных пользователей?

В групповых политиках, конфигурации пользователя, административных шаблонах, в настройках меню "Пуск" отключите необходимые элементы.

Пример:

Конфигурация пользователя -> Настройка -> Параметры панели управления -> Главное меню

Win2008adm.jpg