簡體   English   中英

C 程序使用 fork 轉換為大寫

[英]C program to convert to upper case using fork

我需要創建一個具有子進程和父進程的程序。 子進程必須將父進程發送的行轉換為大寫,父進程必須將行發送給子進程進行轉換,並通過標准輸入顯示轉換后的行。 我已經有了這個,但是當我在終端上執行時,大寫行沒有顯示。

任何建議

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <ctype.h>

int main(void) {
  int p1[2];
  int p2[2];
  pid_t pid;
  char buffer[1024];
  FILE *fp1;
  FILE *fp2;

  pipe(p1);
  pipe(p2);

  pid = fork();
  if (pid < 0) {
    fprintf(stderr, "Error fork\n");
    exit(1);
  }

  if (pid == 0) {
    // Close pipes entrances that aren't used
    close(p1[1]);
    close(p2[0]);

    // Open file descriptors in used entrances
    fp1 = fdopen(p1[0], "r");
    fp2 = fdopen(p2[1], "w");

    // Read from the corresponding file descriptor (pipe extreme)
    while (fgets(buffer, 1024, fp1) != NULL) {
      for (int i = 0; i < strlen(buffer); i++) {
        buffer[i] = toupper(buffer[i]);
      }
      fputs(buffer, fp2);
    }

    // Once finished, close the reaming pipes entrances
    fclose(fp1);
    fclose(fp2);
    exit(1);
  }

  // Close unused pipes entrances
  close(p1[0]);
  close(p2[1]);

  // Open dile descriptors
  fp1 = fdopen(p1[1], "w");
  fp2 = fdopen(p2[0], "r");

  while (fgets(buffer, 1024, stdin) != NULL) {
    fputs(buffer, fp1);       // Send buffer to write line pipe
    fgets(buffer, 1024, fp2); // Get buffer readed from read line pipe
    printf("%s", buffer);     // Print in stdout the buffer
  }

  // Once finished, close the reaming pipes entrances
  fclose(fp1);
  fclose(fp2);

  // Wait fork
  wait(NULL);

  return 0;
}

When using a FILE * stream and the C library stream API, it's important to keep in mind that I/O operations can be "buffered". 在大多數情況下,默認情況下,當通過fputs(...)執行寫入時,字節實際上不會被發送到底層文件 object(在這種情況下是 pipe 結束),直到緩沖區被刷新。 在上面的代碼中,您可以在兩次調用fputs(...)之后添加對fflush(fpN)的調用(其中 N 與代碼中的數字匹配)。 這應該有助於解決您的問題。

請注意,另外還有一些方法可以手動更改給定文件 stream 的緩沖模式。 此信息可以在man setbuf中找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM