int main()
{
char buff[1024] = {0};
FILE* cvt;
int status;
/* Launch converter and open a pipe through which the parent will write to it */
cvt = popen("converter", "w");
if (!cvt)
{
printf("couldn't open a pipe; quitting\n");
exit(1)
}
printf("enter Fahrenheit degrees: " );
fgets(buff, sizeof (buff), stdin); /*read user's input */
/* Send expression to converter for evaluation */
fprintf(cvt, "%s\n", buff);
fflush(cvt);
/* Close pipe to converter and wait for it to exit */
status=pclose(cvt);
/* Check the exit status of pclose() */
if (!WIFEXITED(status))
printf("error on closing the pipe\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int pipefd[2];
pipe(pipefd);
int pid = fork();
if (pid < 0) {
fprintf(stderr, "failed to fork process");
}
else if (pid == 0) {
// the child process doesn't use the pipe's write and thus it closes it.
close(pipefd[1]);
// read data from the pipe's read end and store into buffer.
char buffer[80];
read(pipefd[0], buffer, sizeof(buffer));
printf("Received string: %s", buffer);
exit(0);
}
else {
// the parent process doesn't use the pipe's read end and thus it closes it.
close(pipefd[0]);
// write string to pipe's write end.
char string[] = "Hello, world!\n";
write(pipefd[1], string, (strlen(string)+1));
exit(0);
}
return(0);
}
8条答案
按热度按时间pobjuy321#
一个普通的管道只能连接两个相关的进程。它是由一个进程创建的,当最后一个进程关闭它时,它就会消失。
named pipe,也被称为FIFO,可用于连接两个不相关的进程,并独立于进程存在;这意味着即使没有人使用它,它也可以存在。FIFO是使用
mkfifo()
库函数创建的。示例
writer.c
字符串
reader.c
型
注意:为了简单起见,上面的代码省略了错误检查。
vwhgwdsa2#
从Creating Pipes in C开始,这向你展示了如何使用管道来派生程序。如果你不想使用fork(),你可以使用named pipes。
此外,您可以通过将
prog1
的输出发送到标准输出并在prog2
中阅读stdin
来获得prog1 | prog2
的效果。您还可以通过打开名为/dev/stdin
的文件来读取标准输入(但不确定其可移植性)。字符串
gzszwxb43#
字符串
并宣读:
型
但是,我认为
fcntl
可以是一个更好的解决方案型
cidc1ykv4#
一个程序写入标准输出的内容可以被另一个程序通过标准输入读取。所以很简单,使用c,写
prog1
来使用printf()
打印一些内容,写prog2
来使用scanf()
读取一些内容。然后运行字符串
myzjeezk5#
Here's a sample:
字符串
该计划的重要步骤是:
popen()
调用,用于建立子进程与父进程中管道之间的关联。fprintf()
调用将管道用作普通文件,以写入子进程的标准输入或从其标准输出读取。1.关闭管道并导致子进程终止的
pclose()
调用。r3i60tvu6#
这个答案可能对未来的谷歌员工有所帮助。
字符串
你可以找到一个高级的双向管道调用例子here。
n3schb8v7#
首先,让程序1将字符串写入
stdout
(就像你希望它出现在屏幕上一样)。然后第二个程序应该从stdin
读取一个字符串,就像用户在键盘上打字一样。然后你运行:字符串
w6mmgewl8#
如果你想在两个进程之间启用通信,你必须确定你是否要派生这些进程。如果你要派生它们,那么你可以使用anonymous pipes。否则,你可以使用named pipes。
匿名管道
假设你在
fork()
之前声明了管道,那么一个子进程将继承父进程的管道,两者都指向管道的相同端。你可以利用这个事实在进程之间发送数据。例如,在下面的程序中,父进程将字符串
Hello World!
发送给子进程,然后子进程显示该字符串。字符串
命名管道
对于命名管道,您将使用文件在不相关的进程之间传输数据。
您可以使用
mkfifo
在shell中创建一个命名管道。或者,您可以使用库函数mkfifo()
在C程序中创建它;您必须首先包含<sys/types.h>
和<sys/stat.h>
库。交互创建命名管道
我们在shell中创建命名管道
pipefd
:型
我们按如下方式实现发送方流程:
型
我们按如下方式实现接收方进程:
型
我们编译这两个程序:
型
运行它们:
型
如输出所示,父进程将字符串发送给子进程,然后子进程显示该字符串。