- 论坛徽章:
- 0
|
一段很简单的输入字符到文件的代码,先是使用系统调用:- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- int fd;
- int pid;
- char msg1[]="Test 1 2 3 ..\n";
- char msg2[]="Hello, hello\n";
- if((fd=creat("testfile",0644))==-1)
- return 0;
- if(write(fd,msg1,strlen(msg1))==-1)
- return 0;
- if((pid=fork())==-1)
- return 0;
- if(write(fd,msg2,strlen(msg2))==-1)
- return 0;
- close(fd);
- return 1;
- }
复制代码 执行后结果:- Test 1 2 3 ..
- Hello, hello
- Hello, hello
复制代码 再使用c的库函数重写该程序:- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- FILE *fp;
- int pid;
- char msg1[]="Test 1 2 3 ...";
- char msg2[]="Hello, hello";
- if((fp=fopen("testfile2","w"))==NULL)
- return 0;
- fprintf(fp,"%s pid:%d\n",msg1,getpid());
- if((pid=fork())==-1)
- return 0;
- fprintf(fp,"%s pid:%d\n",msg2,getpid());
- fclose(fp);
- return 1;
- }
复制代码 执行后结果是:- Test 1 2 3 ... pid:8795
- Hello, hello pid:8795
- Test 1 2 3 ... pid:8795
- Hello, hello pid:8796
复制代码 为什么使用库函数的时候父进程会打印三次,我完全不能理解。 |
|