简体   繁体   中英

C program to convert to upper case using fork

I need to create a program that has a child process and a parent process. The child process has to convert lines sent by the parent proccess in to upper case, and the parent proccess has to send lines to the child proccess to convert, and show this converted lines by stdin. I already have this, but at the time when i execute on my terminal, the upper case lines doesn't show.

Any sugestion

#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". In most cases, by default, when performing writes via fputs(...) the bytes will not actually be sent to the underlying file object (a pipe end in this case) until the buffer is flushed. In your code above, you could add calls to fflush(fpN) (where N matches the numbers in your code) after both calls to fputs(...) . This should help fix your problem.

Note that alternatively there are ways of manually changing the buffering mode of a given file stream. This information can be found in man setbuf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM