gpt4 book ai didi

c - UNIX C编程输入重定向命令

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:47 25 4
gpt4 key购买 nike

我正在尝试执行以下简单的 UNIX 命令:

cat -n < file.txt

其中 file.txt 只包含一个整数“5”。

我对输出重定向没问题,但是这个输入重定向让我很困惑。这是我模拟上述命令的尝试:

int f_des[2];
char *three[]={"cat", "-n", NULL};

// Open a pipe and report error if it fails
if (pipe(f_des)==-1){
perror("Pipe");
exit(1);
}

int filed=open("file.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);

//fork child
if(fork()==0){
dup2(f_des[1], filed);
close(f_des[0]);
}

//fork child
if(fork()==0){
dup2(f_des[0], fileno(stdin));
close(f_des[1]);
execvp(three[0], three);
}

我收到以下错误:

cat: -: Input/output error

我的想法是,我通过管道发送 filed(文件的 fd),管道的另一端将从管道收集文件内容作为标准输入,然后我将执行“cat -n”文件内容位于标准输入中。

最佳答案

您没有说明上下文。如果您只想执行 cat -n < file , 你可以省去 pipefork完全。

这应该足够了:

filed = open("file.txt", O_RDONLY);
dup2(filed, 0); // make file.txt be stdin.
close(filed);
execvp(three[0], three);

如果您在另一个程序中实现它并且需要在 cat 之后恢复打电话,fork是必要的,但你只需要调用一次。你不需要 pipe .

所以你会这样做:

int ret;
if ((ret = fork()) == 0) {
// in child
// open file, dup2, execvp...
}

// in parent
wait(&ret); // wait for child to exit
// do other stuff...

fork克隆进程的副本。除了 PID 和来自 fork 的返回值外,它看起来像您以前的那个.

检查 fork() 的返回值可以告诉您该进程是子进程还是父进程。

如果返回值为零,则您在 child 中。在 if(ret == 0) {} 做自己喜欢的事部分。在你的情况下,你做 execvp最终退出并带走 child 。

如果返回值不为零,说明你在父级。您将跳过 if(ret == 0) {}部分。你应该wait让 child 在继续之前退出。

关于c - UNIX C编程输入重定向命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26707905/

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