为什么在IPC的代码中打印时间相同

我编写了一段代码来理解IPC和读写函数的基本知识。 由于读取function是阻塞的,因此读取将等待,直到其他进程将数据写入管道的另一端。 我在父进程中的write()之前进行了sleep调用。 在read()之前和之后的子进程中,我有打印时间。

#include  int main() { int fd[2], err, pid; FILE *fp; char *buf; buf = malloc(12); fp = fopen("BE1.txt","w"); err = pipe(fd); if(err == -1) printf("Error while creating pipe"); pid = fork(); if(pid == -1) printf("Error while creating process"); if(pid == 0) { fprintf(fp,"before read %s\n", __TIME__); // fflush(fp); read(fd[0], buf, 12); fprintf(fp,"%s\n", buf); // fflush(fp); fprintf(fp,"after read %s\n", __TIME__); } else { sleep(50); write(fd[1], "this is it", 12); } fclose(fp); return 0; } 

由于读取处于阻塞模式,子进程应在上面的代码中打印不同的时间。 但它的打印时间相同

输出:

 before read 19:48:16 this is it after read 19:48:16 

为什么会这样?

__TIME__是预定义的#define宏,在编译时进行评估,即当编译器看到__TIME__ ,他将用当前时间替换它。

gcc文档说:

__TIME__

此宏扩展为一个字符串常量,该常量描述预处理器的运行时间。 字符串常量包含八个字符,看起来像"23:59:01"

如果GCC无法确定当前时间,它将发出警告消息(每次编译一次), __TIME__将扩展为"??:??:??"

 __TIME__ 

定义编译的时间!

__TIME__ ,如__FILE____LINE__ ,是一个预处理器宏,可以扩展到预处理器运行的时间(通常作为编译器的一部分)。 所以,它是一个固定的字符串 – 你的代码最终会像编译一样

 fprintf(fp,"after read %s\n", "19:49:16"); 

具体取决于您编译代码的确切时间。

对于定时操作,请改用clock

添加上面的所有优秀答案:

如果你想打印时间,那么怎么样:

 void printCurrentTime() { time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo); puts (buffer); } 

如前所述, __TIME__在编译时而不是运行时进行评估。

如果你想在运行时的实际时间,你需要使用如下: –

  time_t t; time(&t); printf("%s", ctime(&t)); 

还有其他方式可以打印获取不同格式的时间和方式。

PS。 你需要包括time.h