【发布时间】:2013-11-15 23:14:28
【问题描述】:
我有一个任务,我必须解决这个问题...我是 C 的完全新手,我仍在努力学习 C。
问题来了
编写一个创建管道和子进程的程序。父母反复设置警报 15 秒。触发警报时,父级计算自启动以来经过的秒数和微秒数,并通过管道将这些发送给子级。在获得信息时,孩子将它们显示在屏幕上。整个持续2分钟。
我已经尝试过这个问题,但我有很多错误..
这是我的解决方案..
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int fd[2], nbytes;
int fd2[2];
pid_t childpid;
char readbuffer1[80];
char readbuffer2[80];
clock_t start, stop;
long count;
double time_sec, time_milli;
const char* time1, time2;
pipe(fd);
pipe(fd2);
childpid = fork();
if(childpid == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
read(fd[0], readbuffer1, sizeof(readbuffer1));
read(fd2[0], readbuffer2, sizeof(readbuffer2));
printf("Received string 1: %s", readbuffer1);
printf("Received string 2: %s", readbuffer2);
}
else
{
start = clock();
/* Parent process closes up output side of pipe */
alarm(15);
/* Send "string" through the output side of pipe */
stop = clock();
time_sec = (double)(stop-start)/CLOCKS_PER_SEC;
time_milli = time_sec*1000;
sprintf(&time1,"%f",time_sec);
sprintf(&time2,"%f",time_milli);
close(fd[0]);
write(fd[1], time1, (strlen(time1)+1));
write(fd2[1], time2, (strlen(time2)+1));
}
return(0);
}
如何让这个运行 2 分钟?我怎样才能重复运行警报 15 秒?请帮忙....
【问题讨论】: