Monday, July 3, 2017

C++ non-blocking proxy check/open

Leave a Comment

I have an issue with a program written in C++. I want to open a SOCKS5 proxy on a free port then check if is ok (check with curl), then release the I/O blocking. This is the code :

C++

main() {     char* s_sockshost = "127.0.0.1";     socks_port = find_empty_port();      if(fork())     {         // child process continues and opens a socks         open_proxy();     }     else     {         // parrent process just checks something then dies               for(int i = 0; i < 20; i++)         {             proxytest = curlsockstest(s_sockshost,socks_port);              if(proxytest)             {                 break;             }              sleep(1);         }          if(proxytest)         {             if(hitdebug >= 3) printf("check_result : is opened on %s",socks_port);              exit(0); // kill just this process         }         else         {             if(hitdebug >= 3) printf("check_result : is bad\n");              kill(getppid(), SIGKILL); // kill both processes         }     } } 

If i do this from cmd like

./proxy; ls -al; 

then it is executing and executes the command after it, but if i do it from PHP or NODEJS it is hanging, like expecting to finish.

NODEJS:

var exec = require('child_process').exec; var cmd = './proxy; ls -al;';   setTimeout(function(){      console.log("Timer");      exec(cmd, function(error, stdout, stderr) {         console.log("error: ");         console.log(error);         console.log();          console.log("stdout: ");         console.log(stdout);         console.log();          console.log("stderr: ");         console.log(stderr);         console.log();     });      console.log("Timer end");  },2000); 

PHP:

<?php  echo "Run start\n"; $array_exec = array(); // exec("./proxy",$array_exec); system("./proxy");  var_dump($array_exec); echo "Run end\n";  ?> 

What is the explination and how can i solve this?

I am thinking to make PHP and NODEJS comunicating with this C++ app with sqlite or something like that...

2 Answers

Answers 1

The system() function would wait until the process is finished and collect the entire output.

You should either use daemon for your C++ or you can simply change it to: ./proxy & and if you don't need output, ./proxy & > /dev/null

<?php echo "Run start\n"; $array_exec = array();  shell_exec("./proxy &",$array_exec); var_dump($array_exec); echo "Run end\n"; ?> 

Answers 2

Node.js

const { spawn } = require('child_process'); const ls = spawn('proxy');  ls.stdout.on('data', (data) => {   console.log(`stdout: ${data}`); });  ls.stderr.on('data', (data) => {   console.log(`stderr: ${data}`); });  ls.on('close', (code) => {   console.log(`child process exited with code ${code}`); }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment