这里测试父进程打开文件 子进程共同写入
//编译
g++ -o f1.o f1.c
g++ -o f2.o f2.c
//执行 &表后台
./f1.o &
//查看文件
tail -f xxf1f2.txt

//f1.c
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>

int main()
{
    int fd;
    //创建 读写
    fd = open("xxf1f2.txt", O_CREAT | O_WRONLY, 0666);
    if (fork() > 0) {
        char *str = "Message from process F1\n";
        int i;
        //每间隔一秒写入一次str
        for (i = 0; i < 200; i++) {
            write(fd, str, strlen(str));
            sleep(1);
        }
        close(fd);
    } else {
        char fdstr[16];
        //将文件描述符 写入fdstr
        sprintf(fdstr, "%d", fd);
        //执行 ./f2 f2 $fdstr
        execlp("./f2.o", "f2.o", fdstr, 0);
        printf("failed to start 'f2': %m\n");
    }
}

//f2.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>

int main(int argc, char **argv)
{
    int fd, i;
    static char *str = "Message from process F2\n";
    //将字符串转换为数字
    fd = strtol(argv[1], 0, 0);

    for (i = 0; i < 200; i++) 
    {
        //写入str
        if (write(fd, str, strlen(str)) < 0)
            printf("Write error: %m\n");
        sleep(1);
    }
        close(fd);
}
posted on 2022-05-30 22:21  彼岸花不开彼岸  阅读(35)  评论(0)    收藏  举报