Linux下进程控制编程(父进程写入数据,子进程读出数据)

//父进程   write   子进程   read
//需要用到的函数  open,write,memset(清空缓存buf),read,fork(创建子进程),sleep,
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void Write()//父进程,写数据
{
        char buf[32] = "hello world!";
        int fd = open("hello.txt",O_CREAT|O_EXCL|O_RDWR,S_IRWXU);
        if(-1 == fd)
        {
                perror("Write open");
                exit(1);
        }

        int ret = write(fd,buf,strlen(buf));
        if(-1 == ret)
        {
                perror("write");
                exit(1);
        }

        close(fd);
}

void Read()//子进程,读数据
{
        char buf[32] = {0};
        int fd = open("hello.txt", O_RDONLY);
        if(-1 == fd)
        {
                perror("Read open");
                exit(1);
        }
        int ret = read(fd,buf,sizeof(buf));
        if(-1 == ret)
        {
                perror("read");
                exit(1);
        }
        printf("child buf :%s\n",buf);
        close(fd);
}

int main()
{
        pid_t pid;

        pid = fork();

        if(-1 == pid)
        {
                perror("fork");
                exit(1);
        }
        else if(0 == pid)
        {
                sleep(1);
                Read();
        }
        else
        {
                Write();
                sleep(1);
        }

        return 0;
}

~               

 

你可能感兴趣的:(Linux系统编程)