在linux编写一个程序,一个进程负责读取文件并统计字符数(两种),另一个进程负责显示字符数
时间: 2024-05-10 21:14:13 浏览: 4
好的,这是一个经典的进程间通信问题,可以使用管道来实现。下面是一个简单的示例程序,其中一个进程读取文件并统计字符数,另一个进程显示字符数。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 1024
int main(int argc, char* argv[]) {
int fd[2];
pid_t pid;
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Child process: read file and count characters
close(fd[0]);
int fd_file = open(argv[1], O_RDONLY);
if (fd_file == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
int count = 0;
while (1) {
ssize_t num_read = read(fd_file, buf, BUF_SIZE);
if (num_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
if (num_read == 0) {
break;
}
for (int i = 0; i < num_read; i++) {
if (buf[i] != '\n' && buf[i] != '\r') {
count++;
}
}
}
char count_str[20];
sprintf(count_str, "%d", count);
if (write(fd[1], count_str, sizeof(count_str)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(fd_file);
close(fd[1]);
exit(EXIT_SUCCESS);
} else {
// Parent process: read character count and display it
close(fd[1]);
char count_str[20];
if (read(fd[0], count_str, sizeof(count_str)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Character count: %s\n", count_str);
close(fd[0]);
exit(EXIT_SUCCESS);
}
}
```
在本示例中,父进程和子进程通过管道进行通信。子进程读取指定的文件并统计字符数,将结果写入管道。父进程从管道中读取字符数并显示它。请注意,这里使用了`fork()`系统调用来创建子进程,并使用`close()`和`dup()`系统调用来关闭和重定向文件描述符。