gpt4 book ai didi

c - 将 execvp 的输出重定向到 C 中的文件中

转载 作者:行者123 更新时间:2023-12-04 00:46:33 25 4
gpt4 key购买 nike

我不知道我做错了什么......但这是正在执行的代码片段:

if (fork() == 0)
{
// child
int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

dup2(fd, 1); // make stdout go to file

execvp("ls","ls");
close(fd);
exit(0);
}
if(wait(&status) == -1)
{
printf("ERROR REDIRECT\n");
}

fileName 已创建,但里面什么都没有。我做错了什么?

最佳答案

我的猜测是 execvp 不起作用,但由于您不处理错误,所以您看不到它。

试试这个:

char *const args[] = {"ls", NULL};
execvp(args[0], args);

/* If this is reached execvp failed. */

perror("execvp");

或者你可以使用复合文字:

execvp("ls", (char *[]){"ls", NULL});

第二个想法:尝试正常运行,不重定向,看看它是如何工作的。

关于c - 将 execvp 的输出重定向到 C 中的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9070177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com