别摸我的键盘 的学生作业:
read
#include
#include
#include
#include
#include
#include
#define PIPE_PATH "./process_pipe"
int main(int argc, const char *argv[])
{
int fd = open(PIPE_PATH,O_RDONLY);
if(fd == -1){
perror("[ERROR] open()");
exit(EXIT_FAILURE);
}
char buf[20];
int ret = read(fd, buf, sizeof(buf));
if(-1 == ret){
perror("[ERROR] read()");
exit(EXIT_FAILURE);
}
buf[sizeof(buf) -1] = '\0';
printf("okk! current time is %s\n", buf);
close(fd);
return 0;
}
write
#include
#include
#include
#include
#include
#include
#include
#include
#define PIPE_PATH "./process_pipe"
char * gettime(){
time_t cur_time;
struct tm *local_tm;
static char buf[20];
cur_time = time(NULL);
if(cur_time == ((time_t) - 1)){
fprintf(stderr, "failed to obtain the current time.\n");
return NULL;
}
local_tm = localtime(&cur_time);
if(local_tm == NULL){
fprintf(stderr, "failed to convert the time.\n");
return NULL;
}
sprintf(buf,"%04d-%02d-%02d %02d:%02d:%02d",local_tm->tm_year + 1900, local_tm->tm_mon+1, local_tm->tm_mday,
local_tm->tm_hour, local_tm->tm_min, local_tm->tm_sec);
return buf;
}
int main(int argc, const char *argv[])
{
int fd;
int ret = access(PIPE_PATH, F_OK);
if(ret == -1){
printf("no exist mkfifo\n");
ret = mkfifo(PIPE_PATH, 0644);
if(ret == -1){
perror("[ERROR] mkfifo()");
exit(EXIT_FAILURE);
}
}
fd = open(PIPE_PATH,O_WRONLY);
if(fd == -1){
perror("[ERROR] open()");
exit(EXIT_FAILURE);
}
char * w = gettime();
#if 1
printf("Current time is %s strlen() %d \n", w,strlen(w));
#endif
ret = write(fd, w, strlen(w));
if(-1 == ret){
perror("[ERROR] write()");
exit(EXIT_FAILURE);
}
close(fd);
return 0;
}