unix 如何使用管道在两个程序之间发送一个简单的字符串?

dm7nw8vv  于 5个月前  发布在  Unix
关注(0)|答案(8)|浏览(95)

我试着在网上搜索,但几乎没有任何资源。一个小例子就足够了。
编辑我的意思是,两个不同的C程序相互通信。一个程序应该发送“嗨”,另一个应该接收它。类似这样的事情。

pobjuy32

pobjuy321#

一个普通的管道只能连接两个相关的进程。它是由一个进程创建的,当最后一个进程关闭它时,它就会消失。
named pipe,也被称为FIFO,可用于连接两个不相关的进程,并独立于进程存在;这意味着即使没有人使用它,它也可以存在。FIFO是使用mkfifo()库函数创建的。

示例

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


注意:为了简单起见,上面的代码省略了错误检查。

vwhgwdsa

vwhgwdsa2#

Creating Pipes in C开始,这向你展示了如何使用管道来派生程序。如果你不想使用fork(),你可以使用named pipes
此外,您可以通过将prog1的输出发送到标准输出并在prog2中阅读stdin来获得prog1 | prog2的效果。您还可以通过打开名为/dev/stdin的文件来读取标准输入(但不确定其可移植性)。

/*****************************************************************************
 Excerpt from "Linux Programmer's Guide - Chapter 6"
 (C)opyright 1994-1995, Scott Burkett
 ***************************************************************************** 
 MODULE: pipe.c
 *****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];

        pipe(fd);

        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                exit(0);
        }
        else
        {
                /* Parent process closes up output side of pipe */
                close(fd[1]);

                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);
        }

        return(0);
}

字符串

gzszwxb4

gzszwxb43#

dup2( STDIN_FILENO, newfd )

字符串
并宣读:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );


但是,我认为fcntl可以是一个更好的解决方案

echo "salut" | code

cidc1ykv

cidc1ykv4#

一个程序写入标准输出的内容可以被另一个程序通过标准输入读取。所以很简单,使用c,写prog1来使用printf()打印一些内容,写prog2来使用scanf()读取一些内容。然后运行

./prog1 | ./prog2

字符串

myzjeezk

myzjeezk5#

Here's a sample

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

字符串
该计划的重要步骤是:

  1. popen()调用,用于建立子进程与父进程中管道之间的关联。
  2. fprintf()调用将管道用作普通文件,以写入子进程的标准输入或从其标准输出读取。
    1.关闭管道并导致子进程终止的pclose()调用。
r3i60tvu

r3i60tvu6#

这个答案可能对未来的谷歌员工有所帮助。

#include <stdio.h>
#include <unistd.h>

int main(){     
     int p, f;  
     int rw_setup[2];   
     char message[20];      
     p = pipe(rw_setup);    
     if(p < 0){         
        printf("An error occured. Could not create the pipe.");  
        _exit(1);   
     }      
     f = fork();    
     if(f > 0){
        write(rw_setup[1], "Hi from Parent", 15);    
     }  
     else if(f == 0){       
        read(rw_setup[0],message,15);       
        printf("%s %d\n", message, r_return);   
     }  
     else{      
        printf("Could not create the child process");   
     }      
     return 0;

}

字符串
你可以找到一个高级的双向管道调用例子here

n3schb8v

n3schb8v7#

首先,让程序1将字符串写入stdout(就像你希望它出现在屏幕上一样)。然后第二个程序应该从stdin读取一个字符串,就像用户在键盘上打字一样。然后你运行:

$ program_1 | program_2

字符串

w6mmgewl

w6mmgewl8#

如果你想在两个进程之间启用通信,你必须确定你是否要派生这些进程。如果你要派生它们,那么你可以使用anonymous pipes。否则,你可以使用named pipes

匿名管道

假设你在fork()之前声明了管道,那么一个子进程将继承父进程的管道,两者都指向管道的相同端。你可以利用这个事实在进程之间发送数据。
例如,在下面的程序中,父进程将字符串Hello World!发送给子进程,然后子进程显示该字符串。

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

字符串

命名管道

对于命名管道,您将使用文件在不相关的进程之间传输数据。
您可以使用mkfifo在shell中创建一个命名管道。或者,您可以使用库函数mkfifo()在C程序中创建它;您必须首先包含<sys/types.h><sys/stat.h>库。

交互创建命名管道

我们在shell中创建命名管道pipefd

$ mkfifo pipefd


我们按如下方式实现发送方流程:

// sender.c
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char* argv[]) {
    int pipefd = open("mypipe", O_WRONLY);

    // write string to pipe.
    char string[] = "Hello, world!\n";
    write(pipefd, string, (strlen(string)+1));

    close(pipefd);

    return(0);
}


我们按如下方式实现接收方进程:

// receiver.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char* argv[]) {
    int pipefd = open("mypipe", O_RDONLY);

    char buffer[80];
    read(pipefd, buffer, sizeof(buffer));
    printf("Received string: %s", buffer);

    close(pipefd);

    return(0);
}


我们编译这两个程序:

$ gcc sender.c -o sender
$ gcc receiver.c -o receiver


运行它们:

$ ./sender &
[1] 97687
$ ./receiver
Received string: Hello, world!


如输出所示,父进程将字符串发送给子进程,然后子进程显示该字符串。

相关问题