gpt4 book ai didi

c - 使用 execv 将一个进程的输出传输到另一进程的程序

转载 作者:行者123 更新时间:2023-11-30 18:03:32 26 4
gpt4 key购买 nike

我正在尝试执行“sudo conntrack -E -p udp -e NEW”命令,然后将该命令的输出通过管道传输到“logger”命令,但这不起作用。有什么明显的问题吗?所以父级是“sudo conntrack ....”,它 fork 了子级“logger ...”

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);
}

}

}

最佳答案

这几乎是正确的,但主要问题是您需要 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");
}

在 child 身上:

    close(0);
dup(fd[0]);

关于c - 使用 execv 将一个进程的输出传输到另一进程的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8319553/

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