#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
pid_t pid;
char *res = "temp";
if (mkfifo(res, 0666) == -1) {
perror("mkfifo");
exit(1);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid > 0)
{
/* 父进程 */
FILE *fp;
fp = fopen(res, "w");
if (fp == NULL)
{
perror("fopen");
exit(1);
}
fprintf(fp, "Hello \n");
fclose(fp);
wait(NULL);
remove(res);
}
else
{
/* 子进程 */
FILE *fp;
char buf[50];
fp = fopen(res, "r");
if (fp == NULL)
{
perror("fopen");
exit(1);
}
fgets(buf, 50, fp);
printf("接受到:%s", buf);
fclose(fp);
}
return 0;
}
可能的问题
如果子进程在父进程写入数据之前就尝试读取数据,那么它可能会阻塞,等待数据到来。
如果多个进程同时写入同一个文件,可能会导致数据混乱。
在父进程和子进程都完成对文件的操作后,需要删除文件。但是,如果子进程在父进程删除文件之后仍试图读取文件,将会导致错误。