简体   繁体   English

尝试从c ++ linux执行命令行代码

[英]Try to execute command line codes from c++ linux

I tried the following code, to communicate with the command line from c++ code. 我尝试了以下代码,从c ++代码与命令行进行通信。

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

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

The gnome-terminal command is executing fine. gnome-terminal命令执行正常。 After I close the terminal, when am expecting the cd to execute, however, is not happening. 关闭终端后,当我期待cd执行时,不会发生。 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. 我期待这个函数让cmd进入主目录,但事实并非如此。 am working in linux 我在linux工作

I tried it even by removing gnome. 我甚至通过删除gnome尝试了它。 simple cd is not working. 简单的CD无法正常工作。 am I doing something rong>? 我在做什么?

If I try ls, it seems to be working fine! 如果我尝试ls,它似乎工作正常!

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/ 如果您想在执行下一行之前运行程序并等待它完成,请在此处查看此页面和示例代码: 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: 但是如果你想运行gnome-terminal并在新创建的窗口中执行命令,请执行以下操作:

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

The system function creates a shell child process to execute the specified command. system函数创建一个shell子进程来执行指定的命令。

cd is a shell command which changes the current working directory of that shell process only. cd是一个shell命令,它仅更改该shell进程的当前工作目录。

So the child's cd probably works fine, but it has no effect on your C++ program, which is a different process. 所以孩子的cd可能工作正常,但它对你的C ++程序没有任何影响,这是一个不同的过程。

Instead, you probably want to look at the Linux system call chdir . 相反,您可能希望查看Linux系统调用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 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. 但是为了改变shell中的工作目录,我还没有想到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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