Child_process not writing binary file?
I am using the npm library child_process library in an electronic project to grab the stdout stream from a C program using spawn. However, when I try to log the output from 'printf' or 'fprintf' captured by child.stdout.on ('data'), nothing is displayed. This is my test code:
#include <stdio.h>
#include <string.h>
int main(){
char buffer[256];
int i = 0;
while(1){
snprintf(buffer, sizeof(buffer), "echo %d\n", i);
printf("%s\n", buffer);
fprintf(stdout, "%s\n", buffer);
system(buffer);
system("sleep 1");
i++;
}
return 0;
}
I know my javascript is correct because the line fetched by the syscall is captured and I tested it with similar loops in ruby ββscript and bash script and they worked just fine.
When I run the binary in a terminal shell everything is output just fine, but when I try to write all three outputs (the first line should be "echo 0 \ n echo 0 \ n 0") with child.stdout.on ("data", (data) => {...}); the only thing I'll get back is, as I said, "0" from the system call. I am at a loss for a solution.
It might seem that when I run this program in the terminal, I cannot use ^ C to terminate it, as it is just picked up by stdin and transferred the screen with the exit.
Here is my javascript if needed:
const { spawn }= require('child_process');
let test;
// Invoked by a button that when clicked calls ipcRenderer.send('test');
ipcMain.on('test', (event, ...args) => {
test = spawn('./a.out', []);
test.stdout.on('data', (data) => {
console.log(data);
});
});
source to share
printf()
/ fprintf()
buffers its default output. You can manually invoke fflush(stdout);
after your calls to fprintf()
to force the buffered output to stdout, or you can turn off buffering entirely with setvbuf(stdout, NULL, _IONBF, 0);
(this must be done once and before any output to stdout).
source to share