我有一个程序A,需要将命令发送到程序B的标准输入,并读回该程序B的输出.(在C中编程,而不仅仅是Linux)
程序A->发送字母A->程序B ProgramA<-B的输出<-ProgramB
我实际上是第一部分,使用popen()将命令发送到B.我确实知道popen只是一种方法.
那么,使用c进行两种方法的最佳方法是什么? 解决方法: 使用posix功能(因此,将在linux和符合posix标准的任何系统上运行),可以结合使用pipe / execl / dup.简而言之,发生的是:
>创建2个管道(一个读取给孩子,一个写入给孩子) >分叉当前进程.这保持打开相同的FD >关闭当前的stdin / stdout.然后使用dup(它使用最低的可用描述符来复制您提供给它的内容) >执行子进程
注意需要冲洗. 父代的代码为:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main ()
{
pid_t pid;
int pipe_in[2]; /* This is the pipe with wich we write to the child process. */
int pipe_out[2]; /* This is the pipe with wich we read from the child process. */
if (pipe (pipe_in) || pipe (pipe_out)) {
fprintf (stderr, "Error in creating pipes!\n");
exit (1);
}
/* Attempt to fork and check for errors */
if ((pid = fork ()) == -1) {
fprintf (stderr, "Error in fork!\n");
exit (1);
}
if (pid) {
/* The parent has the non-zero PID. */
char temp[100];
int result;
FILE* child_in;
FILE* child_out;
child_in = fdopen(pipe_out[0],"r");
child_out = fdopen(pipe_in[1],"w");
close(pipe_out[1]);
close(pipe_in[0]);
fprintf(child_out, "something\n");
fgets(temp,100,child_in);
printf(" Read from child %s \n", temp);
/* Send a command to the child. */
fprintf(child_out, "quit\n");
fflush(child_out);
fgets(temp,100,child_in);
printf(" Read from child %s \n", temp);
wait (&result); /* Wait for child to finish */
}
else {
/* The child has the zero pid returned by fork*/
close (1);
dup (pipe_out[1]); /* dup uses the lowest numbered unused file descriptor as new descriptor. In our case this now is 1. */
close (0); /* dup uses the lowest numbered unused file descriptor as new descriptor. In our case this now is 0. */
dup (pipe_in[0]);
close (pipe_out[0]);
close (pipe_out[1]);
close (pipe_in[0]);
close (pipe_in[1]);
execl ("child", "child", NULL);
exit(1); /* Only reached if execl() failed */
}
return 0;
}
一个简单的孩子是:
#include <stdio.h>
#include <string.h>
int main ()
{
char temp[100];
do {
printf ("In child: \n");
fflush (stdout);
fgets (temp, 100, stdin);
printf ("Child read %s\n", temp);
fflush (stdout);
} while (!strstr (temp, "quit"));
return 0;
}
您可以使用以下命令进行编译:
gcc -o parent parent.c
gcc -o child child.c
./parent
你会看到
从儿童中读取在儿童中: 从孩子那里读孩子已经退出 来源:https://www./content-4-515951.html
|