简体   繁体   中英

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??

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'");

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM