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

来源:互联网 发布:成都办公软件机构 编辑:程序博客网 时间:2024/06/16 21:14
编写两个不同的可执行程序,名称分别为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");}

原创粉丝点击