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

编写两个不同的可执行程序,名称分别为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");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值