Here is my Node.JS code
var rec = spawn('rec.exe');
rec.stdout.setEncoding('ascii');
rec.stdout.on('data', function (data) {
console.log(data);
//do something
}
);
And my C++ program (compiled by Cygwin) writes something to stdout using printf().
if(bufsize!=0&&rec[0]=='0')
{
printf("%s\n",rec);
//printf("Received,write into exchange file\n");
//fp=fopen("recvdata.txt","w");
//fprintf(fp,"%s\n",rec);
//fclose(fp);
}
But the data event is never emitted.
I'm sure there is something wrong with my C++ code because it works with some other commands like ping.
Then I noticed that in this case, the event is emitted
if(fd==-1)
{
printf("Failed,again\n");
return 0;
}
It means when the process exits, everything works fine. But that's not what I want.
Can someone help me? Thanks.
It sounds like you've got a buffering issue with your C++ program; it's probably not automatically flushing stdout
's buffers with each line, so all the output "bunches up" until it exits. I know there are some ioctl
settings that it could use to change that, but I've long since forgotten what they are. A search on "stdout buffering" might bring up something useful.