简体   繁体   English

在C中使用exec命令执行带有输出重定向的命令

[英]Execute command with output redirection using exec command in C

I need execute a command which redirects output to /dev/null. 我需要执行一个将输出重定向到/ dev / null的命令。 How to execute commands like this using exec in C ? 如何在C中使用exec执行类似的命令?

My command is ls logs/ >/dev/null 2>/dev/null . 我的命令是ls logs/ >/dev/null 2>/dev/null To execute this command, I am first splitting the command with space as delimiter and then executing using exec. 要执行此命令,我首先使用空格分隔定界符,然后使用exec执行。 When executing >/dev/null 2>dev/null are passed as arguments to the script. 执行>/dev/null 2>dev/null作为参数传递给脚本。 How we can avoid this ? 我们如何避免这种情况?

I don't want to use system command to overcome this problem. 我不想使用系统命令来解决此问题。

CODE : 代码:

static int
command_execute(char* command) {
        char **arguments = g_strsplit(command, " ", 32);
        pid_t child_pid;

        if( !arguments ) {
            status = COMMAND_PARSE_ERROR;
            goto EXIT;
        }

        if( (child_pid = fork() ) == -1 ) {
            status = CHILD_FORK_ERROR;
            goto EXIT;
        }

        if( child_pid == 0 ) {
            execvp(arguments[0], arguments);
        } else {
            waitpid(child_pid, &status, 0);
            if(status) {
                goto EXIT;
            }
        }
}

Redirections are not arguments to a command. 重定向不是命令的参数。

In a shell command containing redirects, the shell will set up the redirects before executing the command. 在包含重定向的shell命令中,shell将在执行命令之前设置重定向。 If you want to mimic this behaviour, you need to do the same thing. 如果要模仿这种行为,则需要做同样的事情。 In your child, before calling exec on the command, reopen stdout and stderr to /dev/null (or whatever you want to redirect them to). 在您的孩子中,在通过命令调用exec之前,将stdout和stderr重新打开到/dev/null (或将它们重定向到的任何文件)。

If you need to extract the redirects from the provided string, you'll need to parse the string the same way the shell would (although you might chose to use a simpler syntax); 如果您需要从提供的字符串中提取重定向,则需要以与Shell相同的方式解析字符串(尽管您可能选择使用更简单的语法); interpret the redirects, and only pass the actual arguments to the command. 解释重定向,并且仅将实际参数传递给命令。

A simple way to reopen stdout is to use dup2 . 重新打开stdout的一种简单方法是使用dup2 The following outline needs error checking added: 以下概述需要添加错误检查:

int fd = open("/dev/null", O_WRONLY);
dup2(fd, 1);  /* Use 2 for stderr. Or use STDOUT_FILENO and STDERR_FILENO */
close(fd);

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

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