简体   繁体   English

C,在一个shell实例中执行多个命令

[英]C , Execute multiple commands in one shell-instance

Is there a way to execute shell-commands in the same shell-instance? 有没有办法在相同的shell实例中执行shell命令? Since, system() leaves the started shell after the command is executed. 因为,在执行命令后, system()离开了启动的外壳程序。

You could always contruct your shell command as a single line command using semicolons. 您始终可以使用分号将shell命令构造为单行命令。 Such as: 如:

cd /home/user;mkdir tmp;ls

Do you mean execute the command in the same terminal that run your program? 您的意思是在运行程序的同一终端中执行命令吗? You can achieve that with popen : 您可以使用popen实现:

#include <stdio.h>

int main() {
    FILE *f = popen("ls", "r");
    char line[1024];
    size_t len;
    while (fgets(line, 1024, f) != NULL) {
        printf("%s", line);
    }
    pclose(f);
    return 0;
}

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

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