在c中使用popen运行多个命令 [英] running multiple commands using popen in c

查看:1127
本文介绍了在c中使用popen运行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C创建一个程序,该程序在linux环境中运行,该环境需要运行多个这样的命令

Im creating a program using C that runs in a linux environment that needs to run multiple commands like this

sudo -s

ls

密码

(假设sudo -s下的命令是需要超级用户才能运行的命令)

(assume that the commands under sudo -s are commands that needs to be super user to be able to run it)

现在,我需要做的是获取这些命令的所有输出以进行进一步处理. 这是代码

Now, what I need to do is get all the output of these commands for further processing. Here's the code

int executeCommand(char *command, char *result)
{
    /*This function runs a command./*/
    /*The return value is the output of command*/

    int nSuccess = -1;
    FILE * fp = NULL;
    char buffer[1035];

    if (command == NULL)
        render("Command is null");

    if (result == NULL)
        render("result is null");
    if (command!=NULL && result!=NULL)
    {
        fp=popen("sudo -s","w");
            fwrite ( " ls", 1, 3, fp);
            fwrite ( " pwd", 1, 4, fp);
        if(fp!=NULL)
        {
            strcpy(result,"\0");
            while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL)
            {
                strcat(result,buffer);
            }
            pclose(fp);
        }   nSuccess=0;

    }

    return nSuccess;
}

问题是我将如何执行ls和pwd并获得输出?谢谢:)

The question is how will I be able to execute ls and pwd and then get it's output? Thank you :)

推荐答案

从形式上讲,您的帖子中没有疑问,但是

Formally speaking, there is no quesion in your post, but

  1. 如果您的问题是sudo -s未执行lspwd:请尝试在fwrite()中添加换行符(也将在shell中键入):

  1. if your problem is that ls and pwd are not executed by sudo -s:Try adding a newline to the fwrite()s (as you would type in your shell as well):

 fwrite ( "ls\n", 1, 3, fp);
 fwrite ( "pwd\n", 1, 4, fp);

(不需要在命令前加上" ")

(a " " before the command shouldn't be neccessary)

在检查fp

如果调用fp=popen("sudo -s","w");,则不能使用fp进行阅读. while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL)将不起作用.如果您想将命令传送到 sudo ,并且想要读取输出,则需要两个管道,这会使事情变得更加复杂,或者您可以重定向的输出到临时文件中,然后读取:

if you call fp=popen("sudo -s","w");, you can't use fp for reading. while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL) won't work. If you want to pipe commands to sudo and want to read the output, you need two pipes what makes things a little more complicated, or maybe you can redirect sudo's output to a temp file and read that afterwards:

char tmpfile[L_tmpnam];
char cmd[1024];
tmpnam( tmpfile );
sprintf( cmd, "sudo -s >%s", tmpfile );
fp = popen( cmd, "w" );
....
pclose(fp);

FILE *ofp = fopen( tmpfile, "r" );
if( rfp != null ) {
    while(fgets(buffer, sizeof(buffer)-1,rfp)!=NULL)
    {
        strcat(result,buffer);
    }
    fclose( rfp );
    remove( tmpfile );
}

这篇关于在c中使用popen运行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆