用C语言实现多进程编程,主进程每隔1秒获取当前系统时间写入某文件,子进程打开该文件,读取文件的内容并显示在屏幕上。
时间: 2023-06-16 16:03:49 浏览: 99
下面是一个使用C语言实现多进程编程的示例程序,其中包括主进程和子进程的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#define FILE_NAME "time.txt"
int main()
{
pid_t pid;
time_t current_time;
struct tm *time_info;
char time_string[80];
FILE *fp;
// 创建子进程
pid = fork();
if (pid < 0) {
fprintf(stderr, "Failed to create child process\n");
exit(1);
} else if (pid == 0) {
// 子进程
char buffer[1024];
int nbytes;
while (1) {
// 打开文件
fp = fopen(FILE_NAME, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open file: %s\n", FILE_NAME);
exit(1);
}
// 读取文件内容
nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp);
if (nbytes < 0) {
fprintf(stderr, "Failed to read file: %s\n", FILE_NAME);
exit(1);
}
// 关闭文件
fclose(fp);
// 将文件内容输出到屏幕上
printf("Current time: %s\n", buffer);
// 每隔1秒读取一次文件
sleep(1);
}
} else {
// 主进程
while (1) {
// 获取当前系统时间
current_time = time(NULL);
time_info = localtime(¤t_time);
strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S\n", time_info);
// 打开文件
fp = fopen(FILE_NAME, "w");
if (fp == NULL) {
fprintf(stderr, "Failed to open file: %s\n", FILE_NAME);
exit(1);
}
// 写入文件内容
fputs(time_string, fp);
// 关闭文件
fclose(fp);
// 每隔1秒写入一次文件
sleep(1);
}
// 等待子进程退出
wait(NULL);
}
return 0;
}
```
在上面的示例程序中,主进程通过调用time函数获取当前系统时间,并将其格式化为字符串后写入指定的文件中。子进程则打开该文件,读取其中的内容并输出到屏幕上。主进程和子进程都使用了sleep函数来控制自己的执行间隔。需要注意的是,在子进程中需要使用fread函数来读取文件内容,而不是fgets函数,因为fgets函数会读取文件中的换行符,从而导致输出结果不正确。