Linux用进程通信来输出时间
时间: 2024-05-11 18:18:54 浏览: 5
在Linux中,可以使用进程间通信(IPC)机制来实现进程间的通信。其中,管道(pipe)是一种常用的IPC方式,可以用来在两个进程之间传递数据。
要输出当前时间,可以通过一个进程获取时间并将其写入管道,另一个进程从管道中读取时间并输出。下面是一个简单的示例代码:
进程1:获取时间并写入管道
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main()
{
int fd[2];
time_t t;
struct tm *tm_info;
char buffer[26];
// 创建管道
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 获取当前时间
time(&t);
tm_info = localtime(&t);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
// 写入管道
write(fd[1], buffer, 26);
close(fd[1]);
return 0;
}
```
进程2:从管道中读取时间并输出
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int fd[2];
char buffer[26];
// 创建管道
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 从管道中读取时间
read(fd[0], buffer, 26);
close(fd[0]);
// 输出时间
printf("Current time: %s\n", buffer);
return 0;
}
```
要运行以上代码,可以使用如下命令:
```
$ gcc process1.c -o process1
$ gcc process2.c -o process2
$ ./process1 | ./process2
```
其中,`|` 连接了两个进程,表示将进程1的输出作为进程2的输入。运行后,进程2会输出当前时间。