- 论坛徽章:
- 0
|
本帖最后由 orochi215 于 2010-10-16 12:04 编辑
书上是这样写的,于是我开始作了如下实验,但没有出现预期结果,希望大家指点指点,文件在被调用的程序中不能打开
1.先新建一个文件file,里面随便写了点内容,设为 “hello world”,再将其设置权限为666.
2.新建一个读写的程序read,接受文件描述符为参数,读取文件的内容
3。新建一个调用的程序main,该程序打开文件file,然后利用函数execl调用read程序
程序实现如下
main.c- #include<stdio.h>
- #include<unistd.h>
- #include<stdlib.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<fcntl.h>
- int main(void)
- {
- int fd = open("./file",O_RDONLY);
- char *c = malloc(512);
- sprintf(c,"%d",fd);
- execl("./read",c,NULL);
- return 0;
- }
复制代码 read.c- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- int main(int argc,char*argv[])
- {
- int fd = atoi(argv[1]);
- char*s = malloc(512);
- read(fd,s,512);
- printf("%s",s);
- return 0;
- }
复制代码 |
|