如何发送使用管道两个程序之间的简单字符串? [英] How to send a simple string between two programs using pipes?

查看:76
本文介绍了如何发送使用管道两个程序之间的简单字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着在网上搜索,但也有几乎没有任何资源。一个小例子就足够了。

I tried searching on the net, but there are hardly any resources. A small example would suffice.

编辑
我的意思是,互相通信两个不同的C程序。一个程序应该送喜,另一个应该接受它。类似的东西。

EDIT I mean, two different C programs communicating with each other. One program should send "Hi" and the other should receive it. Something like that.

推荐答案

一个普通管只能连接两个相关的过程。它是由一个进程创建并在最后一个进程关闭它会消失。

A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.

一个命名管道 ,也称为FIFO为它的行为,可以用于连接两个不相关的进程和独立的处理的存在;这意味着它可以即使没有人在使用它存在。 FIFO是使用 mkfifo子()创建 库函数。

A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo() library function.

writer.c

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";

    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);

    /* write "Hi" to the FIFO */
    fd = open(myfifo, O_WRONLY);
    write(fd, "Hi", sizeof("Hi"));
    close(fd);

    /* remove the FIFO */
    unlink(myfifo);

    return 0;
}

reader.c

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";
    char buf[MAX_BUF];

    /* open, read, and display the message from the FIFO */
    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %s\n", buf);
    close(fd);

    return 0;
}

<子>注意:检查从上述code为简化起见,省略错误

这篇关于如何发送使用管道两个程序之间的简单字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆