簡體   English   中英

execvp shell 命令與 shell output 重定向不起作用

[英]execvp shell command with shell output redirection does not work

我開發了以下代碼:主要:

#include<stdio.h>
#include<unistd.h>

int main()
{
    char *const args[] = {"/bin/ls", "> test.txt 2>&1", NULL};
    execvp(args[0], args);

    /* If this is reached execvp failed. */

    perror("execvp");
    return 0;
}

我需要執行這個 shell 命令: /bin/ls > test.txt 2>&1但我有一個錯誤:

$gcc -o main main.c 
$ vi main.c
$ gcc -o main main.c 
$ ./main 
/bin/ls: cannot access '> test.txt 2>&1': No such file or directory
$ 

為什么它返回/bin/ls: cannot access '> test.txt 2>&1': No such file or directory 你有解決方案嗎?

不,那是行不通的。 重定向是 shell 的 function。 通過使用其中一個exec函數,您可以完全繞過 shell。 所以你需要自己處理重定向。

int out = open("test.txt", O_WRONLY | O_CREAT, 0644);
dup2(out, 1);
dup2(out, 2);
close(out);
execvp(args[0], args);

但首先將第二項放在 args 中。

這將打開 output 文件並將其復制到標准輸入和標准輸出,就像 shell 一樣。 最后關閉原始描述符,因為不再需要它。

我省略了錯誤檢查,但你當然應該添加它。

重定向由 shell 解釋。 但是execvp()不運行 shell。 它運行一個可執行文件。 您可以通過調用“sh -c”來執行system()內部完成的操作:

#include<stdio.h>
#include<unistd.h>

int main(void)
{
    char *const args[] = {"/bin/sh", "-c", "/bin/ls > test.txt 2>&1", NULL};
    execvp(args[0], args);

    /* If this is reached execvp failed. */

    perror("execvp");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM