用C语言实现多进程编程,主进程每隔1秒获取当前系统时间写入某文件,子进程打开该文件,读取文件的内容并显示在屏幕上。
时间: 2023-06-16 16:04:40 浏览: 67
以下是一个简单的多进程编程示例,其中主进程每隔1秒钟向文件中写入当前系统时间,子进程打开该文件并读取其中的内容并显示在屏幕上。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
void child_process(FILE *fp) {
char buffer[1024];
while(fgets(buffer, 1024, fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
int main() {
pid_t pid;
FILE *fp;
// 创建文件
fp = fopen("time.txt", "w");
if(fp == NULL) {
printf("无法创建文件\n");
return 1;
}
// 创建子进程
pid = fork();
if(pid < 0) {
printf("无法创建子进程\n");
return 1;
}
else if(pid == 0) {
// 在子进程中运行
child_process(fp);
return 0;
}
else {
// 在主进程中运行
while(1) {
time_t current_time = time(NULL);
char *time_string = asctime(localtime(¤t_time));
fprintf(fp, "%s", time_string);
fflush(fp);
sleep(1);
}
// 等待子进程结束
int status;
wait(&status);
}
return 0;
}
```
在该示例中,我们使用了 `fork()` 函数创建子进程。子进程调用 `child_process()` 函数来打开并读取文件的内容。主进程则在一个无限循环中每秒钟写入当前系统时间到文件中。请注意,我们使用 `fflush(fp)` 函数来确保数据被立即写入文件而不是缓存在内存中。最后,主进程调用 `wait()` 函数等待子进程结束,并检查子进程的返回状态。