c - 执行 execve() 的正确步骤是什么?

标签 c pipe system-calls execve

我们的作业需要使用 pipe()、fork()、execve() 和 dup() 来实现一个带有管道的终端命令的简单执行。因此,我了解了 dup 和 pipe 如何操作文件描述符,并生成了下面的代码。

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

int main(void)
{
    int pfds[2];
    pipe(pfds);

    if (!fork()) {
        close(1);       /* close normal stdout */
        dup(pfds[1]);   /* make stdout same as pfds[1] */
        close(pfds[0]); /* we don't need this */
        char *k = {"echo", "one", "two", "three", NULL};
        execve("/bin/echo", k, NULL);
    } else {
        close(0);       /* close normal stdin */
        dup(pfds[0]);   /* make stdin same as pfds[0] */
        close(pfds[1]); /* we don't need this */
        char *k = {"wc", "-w", NULL};
        execve("/usr/bin/wc", k, NULL);
    }

    return 0;
}

看起来运行代码没有任何结果,我不确定我还需要什么才能让它工作。

我期待输出 3,您将通过输入看到

回显一二三 | wc -w 在终端中。顺便说一下,我使用的是 MacOS。

最佳答案

问题是您将字符串数组分配给 char*。两个 k 都应该声明为 char* k[] = …。如果您的编译器没有就此向您发出警告,您需要启用更多警告。

与评论相反,您正确使用了 closedup(但 dup2 会更好)。

关于c - 执行 execve() 的正确步骤是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245103/

相关文章:

java - 重定向 java 和 javac 输出

c - 在 C 中多次从 stdin 读取相同的数据

c - shell脚本中的后台进程收到EOF

linux - "Segmentation fault",x86_64 程序集,AT&T 语法

c - for循环的操作

c - malloc、memset 和 free 的正确用法

c - 如何在循环中从服务器向客户端接收和发送数据

angular - 如何使用 Angular 搜索管道显示未找到记录消息

c++ - <ctime> 中的 clock() 函数如何访问系统时钟?

c - 使用一组有限的操作对 2 个 50000 个数字的链表进行排序