我尝试重定向 exec 函数输入,使用管道输出结果。这段代码工作正常,但我无法退出下面的 execlp 函数,它总是需要新的输入,但我只想运行一次。如何在第一次输入后停止它。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char *argv[])
{
int chi_pipe[2], par_pipe[2];
if (pipe(chi_pipe) == -1 || pipe(par_pipe) == -1)
ERR_EXIT("pipe error");
pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error");
if (pid == 0)
{
close(chi_pipe[0]); // I don't read in channel 1
close(par_pipe[1]); // I don't write in channel 2
close(STDIN_FILENO);
dup(par_pipe[0]);
execlp("tr", "tr", "/a-z/", "/A-Z/", NULL);
close(chi_pipe[1]);
close(par_pipe[0]);
_exit(0);
}
close(par_pipe[0]);
close(chi_pipe[1]);
write(par_pipe[1], "haha\n", 5);
char buf[3024] = {0};
read(chi_pipe[0], buf, 1024*3);
printf("buf=%s", buf);
printf("\n");
close(par_pipe[1]);
close(chi_pipe[0]);
return 0;
}
最佳答案
我想你想要这个。
将关闭位置向上移动,以便读取可以知道它不会再得到了。
write(par_pipe[1], "haha\n", 5);
close(par_pipe[1]);
你似乎也错过了子段中标准输出的复制,
关于c - 如何在 c 中结束重定向的 execlp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457325/