本文目标:通过文件描述符共享,实现父子进程通信
代码段
#include<stdio.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
int main()
{
FILE* fp;
if((fp=fopen("test.txt","w+"))==0)
{
perror("open error\n");
exit(-1);
}
signal(SIGCHLD,SIG_IGN);
pid_t pid;
pid=fork();
char buf[20];
memset(buf,0,20);
strcpy(buf,"hello,world");
if(pid==0)
{
fprintf(fp,buf);
printf("fd=%d\n",fileno(fp));
fclose(fp);
}else{
//sleep(2);
sleep(1);
printf("ftell=%d\n",ftell(fp));
printf("fd=%d\n",fileno(fp));
rewind(fp);
memset(buf,0,sizeof(buf));
if(fgets(buf,20,fp)==0)
{
perror("read error\n");
exit(-1);
}
printf("buf=%s\n",buf);
fclose(fp);
}
return 0;
}
运行结果