![](/img/trans.png)
[英]How can I execute cat command using execvp or other kinds of exec functions in programming C
[英]Execute command with output redirection using exec command in C
我需要執行一個將輸出重定向到/ dev / null的命令。 如何在C中使用exec執行類似的命令?
我的命令是ls logs/ >/dev/null 2>/dev/null
。 要執行此命令,我首先使用空格分隔定界符,然后使用exec執行。 執行>/dev/null 2>dev/null
作為參數傳遞給腳本。 我們如何避免這種情況?
我不想使用系統命令來解決此問題。
代碼:
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;
}
}
}
重定向不是命令的參數。
在包含重定向的shell命令中,shell將在執行命令之前設置重定向。 如果要模仿這種行為,則需要做同樣的事情。 在您的孩子中,在通過命令調用exec
之前,將stdout和stderr重新打開到/dev/null
(或將它們重定向到的任何文件)。
如果您需要從提供的字符串中提取重定向,則需要以與Shell相同的方式解析字符串(盡管您可能選擇使用更簡單的語法); 解釋重定向,並且僅將實際參數傳遞給命令。
重新打開stdout的一種簡單方法是使用dup2
。 以下概述需要添加錯誤檢查:
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.