help opening shell scripts using C++

Discussion in 'Mac Programming' started by darshie76, Nov 6, 2008.

  1. darshie76 macrumors member

    Joined:
    Sep 4, 2008
    #1
    Hi everyone

    I moved from Win to MAc, and i am trying to integrate some functionalities in a c++ script.

    The idea is to use the c++ script to launch various shell scripts in terminal, getting data from them and passing it to the C++ script

    Now the issue that i have is....how you open terminal from c++ to execute a script? i tried system("terminal.app -x bash myscript"), but i get an error that says that

    sh: terminal: command not found

    Is there any tutorial or example about how to launch scripts in C++ on a mac (found stuff for bat files on pc, not on mac)? i would love to do all in c++ but i am still learning how to deal with ssh connections, so is easier to write a script for that and other operations that i do on my mac.

    Thanks for your help in advance!
     
  2. yeroen macrumors 6502a

    yeroen

    Joined:
    Mar 8, 2007
    Location:
    Cambridge, MA
    #2
    The system() call opens a shell so you don't need to open another one to execute your script. Likewise terminal.app is the GUI I/O handler for the shell, not the shell itself, so you can forget about that as well. Simply do:

    system("./myscript")
     
  3. darshie76 thread starter macrumors member

    Joined:
    Sep 4, 2008
    #3
    Thanks a lot yeroen!

    now i have a doubt about what happens to the results of the script:

    if i launch my script that

    -connects via ssh to a server
    -retrieve the logs using a grep statement

    the output would be on standard out, that is the terminal screen...in this case what happens to the data? as soon as the call is over the data is lost since the process returns NULL?

    I am planning to get the output of the script and save it in variables...is that possible? or should i direct the script to save teh output to a file and open it in c++ as stream and work with it?

    Thanks again!
     
  4. yeroen macrumors 6502a

    yeroen

    Joined:
    Mar 8, 2007
    Location:
    Cambridge, MA
    #4
    I'd use popen() here rather than system(). popen() returns an I/O stream from which you can capture your shell scripts output.
     
  5. ChrisA macrumors G4

    Joined:
    Jan 5, 2006
    Location:
    Redondo Beach, California
    #5
    The thing to remember is that the Mac is just Unix. Nothing special or Mac-specific is required. When you need figure something like this out the best place is the man pages. For example start some place like the system(2) man page then notice down at the bottom where it says "See Also" and then read those and then yo would have found "popen".

    That said, I think Perl is more suited to your task.
     

Share This Page