c_cpp 管道示例:从进程中读取字符并在另一个进程中以大写形式显示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 管道示例:从进程中读取字符并在另一个进程中以大写形式显示相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#define N 132

void sender (pid_t, int []);
void receiver (int []);

int
main (int argc, char **argv) {
  int fd[2];
  int cpid, status;
  int receiverPid, senderPid;

  pipe (fd);

  receiverPid = fork();
  if (receiverPid == 0) {
    receiver (fd);
  } else {
    senderPid = fork();
    if (senderPid == 0) {
      sender (receiverPid, fd);
    }
  }

  fprintf (stdout, "Sender   PID %d\n", senderPid);
  fprintf (stdout, "Receiver PID %d\n", receiverPid);

  cpid = wait(&status);
  cpid = wait(&status);

  return (0);
}

void sender (pid_t receiverPid, int fd[2]) {
  char line[N], tmp[N];
  int sentMsg=0, senderPid;

  close (fd[0]);
  senderPid = getpid();

  while (1) {
    fprintf (stdout, "SENDER (receiverPid=%d): ", receiverPid);
    fflush (stdout);
    scanf ("%s", line);

    sprintf (tmp, "%5d%s", senderPid, line);
    write (fd[1], tmp, (strlen(tmp)+1));

    sentMsg++; 	
    if (strcmp (line, "end") == 0)
      break;

    sleep (1);
  }

  exit(sentMsg); 
}

void receiver (int fd[2]) {
  char line[N], tmp[N];
  int receivedMsg=0, senderPid, i;
  
  close (fd[1]);

  while (1) {
    read (fd[0], tmp, N);
    sscanf (tmp, "%5d%s", &senderPid, line);
    if (strcmp(line, "end") == 0)
      break;
              
    for (i=0; i<strlen (line); i++) {
      line[i] = toupper (line[i]);
    }
    fprintf (stdout, "RECEIVER (senderPid=%d): %s\n", senderPid, line);
    fflush (stdout);
    receivedMsg++;     
  }  

  exit (receivedMsg); 
}

以上是关于c_cpp 管道示例:从进程中读取字符并在另一个进程中以大写形式显示的主要内容,如果未能解决你的问题,请参考以下文章

Linux pipe():从管道读取并不总是解除对写入器的阻塞

在 C++ 中使用管道和超时执行命令(并读取标准输出)

使用管道从 STDIN 读取分叉进程的问题

Linux - 从管道读取的孩子接收发送到标准输出的调试消息

c_cpp 从STDIN读取字符串并将其打印到STDOUT的示例C代码。

linux学习之进程篇