What is spawn windows

pghalliday / 1 test.js

var http = require ( ‘http’ ) ;
var spawn = require ( ‘child_process’ ) . spawn ;
var child = spawn (
‘CMD’ , [
‘/S’ ,
‘/C’ ,
‘node’ ,
‘./child.js’
]
) ;
child . stdout . pipe ( process . stdout ) ;
child . stderr . pipe ( process . stderr ) ;
child . on ( ‘exit’ , function ( ) <
http . get ( ‘http://localhost:8080’ , function ( response ) <
console . log ( ‘child did NOT die’ ) ;
> ) . on ( ‘error’ , function ( error ) <
console . log ( ‘child did die’ ) ;
> ) ;
> ) ;
setTimeout ( function ( ) <
http . get ( ‘http://localhost:8080’ , function ( response ) <
response . on ( ‘end’ , function ( ) <
console . log ( ‘kill the child’ ) ;
child . kill ( ) ;
> ) ;
> ) ;
> , 2000 ) ;
var http = require ( ‘http’ ) ;
var PORT = 8080 ;
var server = http . createServer ( function ( request , response ) <
response . end ( ) ;
> ) ;
server . listen ( PORT , function ( ) <
console . log ( ‘Listening on port ‘ + PORT ) ;
> ) ;
V:\GitHub\node-ChildDaemon\test\Spikes\windows>node test.js
Listening on port 8080
kill the child
child did NOT die
*********
I can kill the process and children with ctrl-c at this point (although i expected it to kill the child and exit on it’s own)

This comment has been minimized.

Copy link Quote reply

Breme commented Feb 7, 2017

Can you Help me on this ?

session.on(‘exec’, function (accept, reject, info) <
console.log(‘Client wants to execute: ‘ + inspect(info.command));
var stream = accept();

When I manually type the first command ‘XXXCLI ip_address’ in my command prompt and press enter,I will get a output «Connected to CLI. » .Once I get this connection successful, I need to execute my second command i.e «Lmc sample» which will load the master config and I will get the output as «Message sent..», third command will execute a script,will get output as «Message sent..» .This is what happens when I enter these commands manually in cmd prompt and execute.

What is happening is once I execute my first command i.e «XXXCLI 10.21.254.12» manually in cmd, The path where we actually execute the commands i.e( C:\users\CLI>) will not be visible. This happens because now it got connected with the above mentioned ip (10.21.254.12) .And Only after connecting to this ip ,I can able to execute my other commands.i.e command to load master config ,cmd to execute script etc.

So I want to execute my first command and get its stream in a variable and execute rest of the commands inside the stream created by first command Thanks!

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Java spawning a Windows process that itself spawns various children

I have a Java application that spawns a Win32 process: Runtime.getRuntime().exec(cmdarray);

The Win32 process will also spawn various subchild using CreateProcess win32 API. When the Java code kills the the win32 process: p.destroy()

The win32 process is destroyed but the children are still alive ! Since p.destroy seems to call the TerminateProcess Win32 API, I can not have handler triggered in my Win32 launcher in order to kill the children.

Читайте также:  Yandex radio mac os

I’ve tried to launch the subChildren with DEBUG_PROCESS option and also tried to use DebugActiveProcess without much success. The DebugActiveProcess returns 50 as GetLastError (operation not permited).

2 Answers 2

Process.destroy() doesn’t give the target process a chance to clean up (and, in particular, clean up their children). Without knowing anything about the processes started, it’s hard to give further guidance.

If you have control over the source of the child processes, then the best choice is to add some sort of IPC so that you can explicitly tell them when to shut down (e.g., a global event).

If you don’t have control over the source of the child processes, then your best choice requires a bit of win32 programming.

What you want to do is iterate over the top-level HWNDs looking for HWNDs owned by the processes you started, and when you find them, post a WM_SYSCOMMAND message with SC_CLOSE to that HWND. This works for both windows apps and console apps.

Node.js Spawn vs. Execute

In an online training video I am watching to learn Node, the narrator says that «spawn is better for longer processes involving large amounts of data, whereas execute is better for short bits of data.»

Why is this? What is the difference between the child_process spawn and execute functions in Node.js, and when do I know which one to use?

4 Answers 4

The main difference is the spawn is more suitable for long-running process with huge output. spawn streams input/output with child process. exec buffered output in a small (by default 200K) buffer. Also as I know exec first spawn subshell, then try to execute your process. To cut long story short use spawn in case you need a lot of data streamed from child process and exec if you need such features as shell pipes, redirects or even you need exec more than one program in one time.

child process created by spawn()

  • does not spawn a shell
  • streams the data returned by the child process (data flow is constant)
  • has no data transfer size limit

child process created by exec()

  • does spawn a shell in which the passed command is executed
  • buffers the data (waits till the process closes and transfers the data in on chunk)
  • maximum data transfer 200kb (by default)

-module.js (baiscally returns a message every second for 5 seconds than exits)

  • the spawn() child process returns the message module data every 1 second for 5 seconds, because the data is ‘streamed’
  • the exec() child process returns one message only module data module data module data module data module data after 5 seconds (when the process is closed) this is because the data is ‘buffered’

NOTE that neither the spawn() nor the exec() child processes are designed for running node modules, this demo is just for showing the difference, (if you want to run node modules as child processes use the fork() method instead)

child_process.spawn fails on Windows given a space in both the command and an argument #25895

Comments

smrq commented Aug 24, 2015

The gist of this issue is that on Windows, child_process.spawn handles the command incorrectly when both it and one of its arguments contains a space. So, this works fine:

Читайте также:  Отключение ждущего режима windows 10

But this yields ‘command’ is not recognized as an internal or external command, operable program or batch file. :

Tested on Windows 7 with node 0.12.7.

The text was updated successfully, but these errors were encountered:

maxrimue commented Aug 25, 2015

I think this happens because Windows tries to execute command with spaces.cmd which won’t work, because Windows doesn’t recognise spaces like that. What happens if you instead try:

smrq commented Aug 25, 2015

Attempting to use spawn on a quoted command like that yields an ENOENT (it seems that the quotes are interpreted as a literal part of the filename, despite quotes being an invalid character in Windows filenames).

You can see this for yourself by updating the repro above with:

Note that spawn handles unquoted commands with spaces, if and only if none of the arguments also have a space. The line you posted works fine when the command file is unquoted. spawn deals with spaces fine in both positions independently, but not at the same time, which is what makes this behavior particularly odd.

maxrimue commented Aug 25, 2015

But aside that problem, why would you even need spaces in the arguments? Could you provide an example?

smrq commented Aug 25, 2015

Sure, an example command that works on the command line might look like:

Which would most naturally translate to:

You can potentially hack around this in a number of ways, depending on the circumstances — in this instance in particular, spawn ing with cwd: «C:\path to test runner» means you won’t have a space in the command file:

. apart from any effects of having a different working directory when executing the command file.

However, I have not been able to imagine a workaround that would work with this situation if the actual filenames contained spaces, not just the directories. Well, other than renaming the files, if that’s within your control.

More specifically, I encountered this problem within gulp-protractor (relevant line), which is fixable with hacking cwd , but I don’t have a general-case workaround because of the possibility of filenames with spaces in them.

sbialobok commented Sep 22, 2015

I’ve similarly run into this issue using grunt-nunit-runner (line). Current workaround is to add the command to the path to avoid having to type «Program Files», but would be great if environment variables didn’t need to be set for this to work.

endquote commented Jan 24, 2016

Another sort-of workaround is to use «PROGRA

1″ instead of «Program Files» in paths. This probably doesn’t work in every Windows configuration, though.

progmars commented Feb 5, 2016

I could not figure out how to use spawn() to call git commit -m «Version update» on Windows but finally I found a strange workaround.

Maybe my issue is different because I’m using command = process.env.comspec || «cmd.exe» to be able to execute various kinds of executable files (exe, cmd etc.)

If I call spawn with arguments «commit», «-m», «\»Version update\»» , (escaped quotes because git expects a quoted string comment) then my final function call arguments look as follows:

Читайте также:  Средство создания windows media

It seems, Windows treats entire string as a command, but has stripped the start quote and the end quote, so the command instead of being

«git» commit -m «Version update»

git» commit -m «Version update

If I remove windowsVerbatimArguments: true , then I get:
‘\»git\»‘ is not recognized as an internal or external command, operable program or batch file.

If I try single quotes «‘Version update'» , then I get
error: pathspec ‘update» did not match any file(s) known to git.

At first I thought that the /s flag is the culprit, but removing it didn’t help at all.

It turned out that /s strips redundant quotes only inside the string but the outer quotes are never preserved. MSDN docs say:

So, finally it came to me that I should always enforce additional quotes like this:

Now finally I can execute files on paths with spaces.

Yeah, Windows is weird. But I guess this workaround with piping everything through cmd shell and enforcing additional quotes around entire command string should work with any command, theoretically.

What is spawn windows

A cross platform solution to node’s spawn and spawnSync.

Node.js version 8 and up: $ npm install cross-spawn

Node.js version 7 and under: $ npm install cross-spawn@6

Node has issues when using spawn on Windows:

  • It ignores PATHEXT
  • It does not support shebangs
  • Has problems running commands with spaces
  • Has problems running commands with posix relative paths (e.g.: ./my-folder/my-executable )
  • Has an issue with command shims (files in node_modules/.bin/ ), where arguments with quotes and parenthesis would result in invalid syntax error
  • No options.shell support on node

All these issues are handled correctly by cross-spawn . There are some known modules, such as win-spawn, that try to solve this but they are either broken or provide faulty escaping of shell arguments.

Exactly the same way as node’s spawn or spawnSync , so it’s a drop in replacement.

Using options.shell as an alternative to cross-spawn

Starting from node v4.8 , spawn has a shell option that allows you run commands from within a shell. This new option solves the PATHEXT issue but:

  • It’s not supported in node
  • You must manually escape the command and arguments which is very error prone, specially when passing user input
  • There are a lot of other unresolved issues from the Why section that you must take into account

If you are using the shell option to spawn a command in a cross platform way, consider using cross-spawn instead. You have been warned.

While cross-spawn adds support for options.shell in node , all of its enhancements are disabled.

This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using options.shell you are probably targeting a specific platform anyway and you don’t want things to get into your way.

While cross-spawn handles shebangs on Windows, its support is limited. More specifically, it just supports #!/usr/bin/env

must not contain any arguments.
If you would like to have the shebang support improved, feel free to contribute via a pull-request.

Remember to always test your code on Windows!

$ npm test
$ npm test — —watch during development

Оцените статью