您的位置:首页 > 运维架构 > Linux

linux 练习三 fork函数和exev函数族

2017-11-29 12:46 253 查看
编写两个不同的可执行程序,名称分别为a和b,b为a的子进程。
在a程序中调用open函数打开a.txt文件。
在b程序不可以调用open或者fopen,只允许调用read函数来实现读取a.txt文件。
(a程序中可以使用 fork与execve函数创建子进程)。

a.c
//fork函数 父子进程 共享(复制)文件描述符

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc,char * argv[])
{
pid_t pid;
int fd;
if(argc < 2)
{
printf("please input 2 para\n");
exit(1);
}
printf("the process pid=%d\n",getpid());
fd = open(argv[1],O_RDONLY,0);
if(fd < 0)
{
perror("open");
exit(1);
}

pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
else if(0 == pid)
{
char buf[10];
sleep(1);
sprintf(buf,"%d",fd);
printf("now is in child process,pid=%d,it's parent pid=%d\n",getpid(),getppid());
if(execl("./b.o","b.o",buf,NULL)<0)
{
perror("execl");
exit(1);
}
}
else
{
if(close(fd) < 0)
{
perror("close");
}
printf("close file over\n");
printf("wait for child process over\n");
pid = waitpid(pid,NULL,0);
printf("child process pid =%d over\n",pid);
}

}
b.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char* argv[])
{
int fd;
int i;
char buf[100];
int readnum;
if(argc < 2)
{
printf("b process please input 2 para\n");
exit(1);
}
printf("now is in b process\n");
for(i = 0;i<argc;i++)
{
printf("argv[%d]=%s\n",i,argv[i]);
}

fd = atoi(argv[1]);
if(fd < 3)
{
printf("b process please input correct fd\n");
exit(1);
}

do{
bzero(buf,sizeof(buf));
readnum = read(fd,buf,sizeof(buf));
printf("%s",buf);
}while(readnum == sizeof(buf));
printf("\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  百炼成钢