Try to execute command line codes from c++ linux

梦想与她 提交于 2020-12-05 06:19:08

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/14532496/try-to-execute-command-line-codes-from-c-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!