Lakshmi Narayanan
Lakshmi Narayanan

Reputation: 5342

Try to execute command line codes from c++ linux

I tried the following code, to communicate with the command line from c++ code.

#include<iostream>
#include<cv.h>

int main()
{
    system("gnome-terminal");
    system("cd");
}

The gnome-terminal command is executing fine. After I close the terminal, when am expecting the cd to execute, however, is not happening. Could you please help me and point out the reason? Thanks. I was expecting the function to make the cmd go down to the home directory , but it did not. am working in linux

I tried it even by removing gnome. simple cd is not working. am I doing something rong>?

If I try ls, it seems to be working fine!

My main aim is to open a new terminal, and execute commands on that new terminal through the present program that opened the new terminal. Could you please tell me how I can achieve this??

Upvotes: 11

Views: 85353

Answers (3)

Vahid Farahmand
Vahid Farahmand

Reputation: 2558

If you want to run a program and wait for it to finish before executing next line, take a look at this page and example code here: http://www.thegeekstuff.com/2012/03/c-process-control-functions/

But if you want to run gnome-terminal and execute a command in newly created window, do this:

system("gnome-terminal -x sh -c 'cd /tmp ; ls -la'");

Upvotes: 11

Lakshmi Narayanan
Lakshmi Narayanan

Reputation: 5342

Thanks for your help!! This command worked perfectly fine from this link

https://superuser.com/questions/198015/open-gnome-terminal-programmatically-and-execute-commands-after-bashrc-was-execu

    gnome-terminal -x sh -c 'command1; command2; exec bash'

and I entered the respective commands in the new window. But to change the working directory in the shell am working o, I haven't still figured that out.

Upvotes: 0

aschepler
aschepler

Reputation: 72271

The system function creates a shell child process to execute the specified command.

cd is a shell command which changes the current working directory of that shell process only.

So the child's cd probably works fine, but it has no effect on your C++ program, which is a different process.

Instead, you probably want to look at the Linux system call chdir.

Upvotes: 7

Related Questions