我正在尝试执行“sudo conntrack -E -p udp -e NEW”命令,然后将此命令的输出传递给“logger”命令,但这不起作用。什么明显的错误? 所以父母是“sudo conntrack ....”,它会让孩子“记录器......”
void main () {
pid_t pid;
int status;
int j=0;
int exe_process;
FILE *prt1;
FILE *prt2;
int fd[2];
char *arg[]={ "sudo", "/usr/sbin/conntrack", "-E", "-p", "udp", "-e", "NEW", NULL };
char *arg1[]={ "/usr/bin/logger", "-t", "log-conntrack", "-p", "daemon.notice", NULL };
if (pipe(fd) < 0)
printf("pipe error\n");
if ((pid = fork()) < 0) /* fork a child process */
{
printf("ERROR: forking child process failed\n");
exit(1);
}
else if (pid > 0) /* for the parent process: */
{
printf("In parent process %d\n",getpid());
close(fd[0]);
if (execvp("/usr/sbin/conntrack", arg) < 0) /* execute the command */
{
printf("ERROR: exec failed\n");
exit(1);
}
prt1=fdopen(fd[1], "ab");
}
else /* for the child: */
{
printf("In parent child %d\n",getpid());
close(fd[1]);
prt2=fdopen(fd[0], "rb");
if (execvp("/usr/bin/logger", arg1) < 0) /* execute the command */
{
printf("ERROR: exec failed\n");
exit(1);
}
}
}
答案 0 :(得分:0)
这几乎是正确的,但主要问题是你需要dup()而不是你想用fdopen
做什么。 dup
将以您想要的方式重定向stdin / stdout。
else if (pid > 0) /* for the parent process: */
{
printf("In parent process %d\n",getpid());
close(fd[0]);
close(1);
dup(fd[1]);
if (execvp("/usr/sbin/conntrack", arg) < 0) /* execute the command */
{
printf("ERROR: exec failed\n");
exit(1);
}
//prt1=fdopen(fd[1], "ab");
}
在孩子身上:
close(0);
dup(fd[0]);